"use client"
import ProjectTabs from "@/components/ProjectTabs";
import ProjectSpecsCard from "@/components/ProjectSpecsCard";
import ProjectHero from "@/components/ProjectHero";
import FeaturesWarranties from "@/components/FeaturesWarranties";
import ProjectLocation from "@/components/ProjectLocation";
import UnitsStatusTabs from "@/components/UnitsStatusTabs";
import { getPropertyById, formatLocationSubtitle, translate, PropertyDetails } from "@/lib/api";
import { notFound, useParams } from "next/navigation";
import { useEffect, useState } from "react";

const ProjectDetails = () => {
  const params = useParams();
  const id = params.id as string;
  const [property, setProperty] = useState<PropertyDetails | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      const data = await getPropertyById(id);
      if (data) {
        setProperty(data);
      }
      setLoading(false);
    };
    fetchData();
  }, [id]);

  if (loading) return <div>Loading...</div>;
  if (!property) {
    notFound();
    return null;
  }

  const mainImage = property.images && property.images.length > 0
    ? property.images[0].url
    : 'public/main-page/propertyProjects/makeen-46.webp';

  const locationString = formatLocationSubtitle(property.address, property.city?.name || '');

  const hasFeatures = property.features && property.features.length > 0;
  const hasWarranties = (property as any).warranties && (property as any).warranties.length > 0;
  const hasLandmarks = (property as any).nearby_landmarks && (property as any).nearby_landmarks.length > 0;
  const hasFacilities = (property as any).internal_facilities && (property as any).internal_facilities.length > 0;

  const mappedFeatures = property.features?.map(f => ({
    name: f.title || '',
    icon: '/main-page/features/feature-check.svg'
  })) || [];

  return (
    <div className="mt-8 px-4 md:px-12 flex flex-col md:flex-row md:items-start gap-6 text-[#05222D]">
      <div className="flex flex-col gap-4 lg:w-3/4 flex-grow">
        <ProjectHero
          image={mainImage}
          isDownloadButtonVisible={true}
          images={property.images}
        />

        <ProjectSpecsCard
          classNames="md:hidden mb-2"
          property={property}
        />

        <div className="bg-[#F1F5F9] p-3 rounded-md">
          <div className="flex items-center gap-2 ">
            <h2 className="text-[#052531] font-bold text-xl">{property.title}</h2>
            {property.type_of_property && (
              <div className="bg-[#0525311A] px-2 py-1 text-xs rounded-full">
                {translate(property.type_of_property)}
              </div>
            )}
          </div>

          <div className="text-[#45556C] text-sm flex items-center gap-1 mt-1 mb-6">
            <MapIcon size={16} />
            {locationString}
          </div>

          <p className="text-[#45556C] text-base">
            {property.description}
          </p>
        </div>

        <UnitsStatusTabs units={(property as any).units || []} />

        <FeaturesWarranties
          features={mappedFeatures}
          warranties={(property as any).warranties || []}
        />

        <ProjectLocation
          address={property.address}
          latitude={property.latitude ? parseFloat(property.latitude) : undefined}
          longitude={property.longitude ? parseFloat(property.longitude) : undefined}
          propertyTitle={property.title}
        />

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="bg-[#F1F5F9] p-3 rounded-md">
            <h3 className="text-[#052531] font-bold text-md">
              المعالم القريبة
            </h3>

            <hr className="my-2 border-[#CAD5E2]" />

            {hasLandmarks ? (
              <div className="grid grid-cols-2 gap-4">
                {(property as any).nearby_landmarks.map((land: any, idx: number) => (
                  <div key={idx} className="flex gap-4">
                    <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M0 6C0 2.68629 2.68629 0 6 0H34C37.3137 0 40 2.68629 40 6V34C40 37.3137 37.3137 40 34 40H6C2.68629 40 0 37.3137 0 34V6Z" fill="#F8FAFC" />
                      <path d="M26 14C26 10.691 23.309 8 20 8C16.691 8 14 10.691 14 14C14 16.968 16.166 19.439 19 19.916V31C19 31.552 19.448 32 20 32C20.552 32 21 31.552 21 31V19.916C23.834 19.439 26 16.968 26 14ZM20 18C17.794 18 16 16.206 16 14C16 11.794 17.794 10 20 10C22.206 10 24 11.794 24 14C24 16.206 22.206 18 20 18Z" fill="#45556C" />
                    </svg>
                    <div>
                      <p className="text-[#45556C] text-sm font-semibold">{land.location}</p>
                      <p className="text-[#62748E] text-sm mt-1">المسافة: {land.distance}</p>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-[#62748E] text-sm text-center py-4">لا توجد بيانات حالياً</p>
            )}
          </div>

          <div className="bg-[#F1F5F9] p-3 rounded-md">
            <h3 className="text-[#052531] font-bold text-md">
              المرافق الداخليه
            </h3>

            <hr className="my-2 border-[#CAD5E2]" />

            {hasFacilities ? (
              <div className="flex flex-col gap-4">
                {(property as any).internal_facilities.map((facility: any, idx: number) => (
                  <div key={idx} className="flex items-center gap-3">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M0 12C0 5.37258 5.37258 0 12 0C18.6274 0 24 5.37258 24 12C24 18.6274 18.6274 24 12 24C5.37258 24 0 18.6274 0 12Z" fill="#F8FAFC" />
                      <path d="M17.3337 8L10.0003 15.3333L6.66699 12" stroke="#1D293D" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                    <p className="text-[#45556C] font-semibold text-sm">{facility}</p>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-[#62748E] text-sm text-center py-4">لا توجد بيانات حالياً</p>
            )}
          </div>
        </div>

        <ProjectTabs property={property} />
      </div >

      <ProjectSpecsCard
        classNames="hidden md:block"
        property={property}
      />
    </div >
  );
};

const MapIcon = ({ size = 20, color = '#314158' }: { size?: number; color?: string }) => {
  return (
    <svg width={size} height={size} viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M17.5 8.33334C17.5 14.1667 10 19.1667 10 19.1667C10 19.1667 2.5 14.1667 2.5 8.33334C2.5 6.34422 3.29018 4.43657 4.6967 3.03004C6.10322 1.62352 8.01088 0.833344 10 0.833344C11.9891 0.833344 13.8968 1.62352 15.3033 3.03004C16.7098 4.43657 17.5 6.34422 17.5 8.33334Z" stroke={color} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M10 10.8333C11.3807 10.8333 12.5 9.71406 12.5 8.33334C12.5 6.95263 11.3807 5.83334 10 5.83334C8.61929 5.83334 7.5 6.95263 7.5 8.33334C7.5 9.71406 8.61929 10.8333 10 10.8333Z" stroke={color} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
};

export default ProjectDetails;