"use client";
import { useState } from "react";
import { ProfileDataType } from "@/type/userType";
import { Card } from "@/components/ui/card";
import Link from "@/public/icon/link.svg";
import Image from "next/image";
import { Textarea } from "@/components/ui/textarea";
import {
  PublicAward,
  PublicCertificate,
  PublicExperience
} from "@/app/(CV)/type/shareProfileType";
import { languageProficiencyOptions } from "@/components/common/CustomDialog";
import { socialIcons } from "@/dummyData/data";
import { MdImageNotSupported } from "react-icons/md";

// ── Section Components (read-only) ──────────────────────────────────────────

const getSocialIcon = (platform?: string) =>
    socialIcons[platform?.toLowerCase() ?? ""] || (
      <MdImageNotSupported className="h-8 w-8" />);

const AboutSection = ({ data }: { data: any }) => (
  <div className="flex flex-col gap-4">
    {data?.about_me && (
      <Card className="gap-0 border-none p-5">
        <h3 className="text-light-gray mb-2 text-[18px]">About Me</h3>
        <p className="font-poppins text-[14px]">{data.about_me}</p>
      </Card>
    )}
    {data?.expertises?.length > 0 && (
      <Card className="gap-0 border-none p-5">
       
        <div className="flex flex-wrap gap-2">
           <h3 className="text-light-gray mb-3 text-[20px]">Expertise</h3>
          {data.expertises.map((item: any) => (
            <span
              key={item.id}
              className="border-border bg-upload-bg group relative flex h-max cursor-pointer items-center justify-center rounded-lg border px-5 py-2 text-[12px] font-medium whitespace-nowrap hover:scale-105"
            >
              {item.name}
            </span>
          ))}
        </div>
      </Card>
    )}
    {data?.skills?.soft?.length > 0 && (
      <Card className="gap-0 border-none p-5">
        <h3 className="text-light-gray mb-3 text-[24px]">Soft Skills</h3>
        <div className="flex flex-wrap gap-2">
          {data.skills.soft.map((item: any) => (
            <span
              key={item.id}
              className="border-border bg-upload-bg group relative flex h-max cursor-pointer items-center justify-center rounded-lg border px-5 py-2 text-[14px] font-medium whitespace-nowrap hover:scale-105"
            >
              {item.name}
            </span>
          ))}
        </div>
      </Card>
    )}
    {data?.skills?.soft?.length > 0 && (
      <Card className="gap-0 border-none p-5">
        <h3 className="text-light-gray mb-3 text-[24px]">Tool Skills</h3>
        <div className="flex flex-wrap gap-2">
          {data.skills.soft.map((item: any) => (
            <span
              key={item.id}
              className="border-border bg-upload-bg group relative flex h-max cursor-pointer items-center justify-center rounded-lg border px-5 py-2 text-[14px] font-medium whitespace-nowrap hover:scale-105"
            >
              {item.name}
            </span>
          ))}
        </div>
      </Card>
    )}
    {data?.skills?.tool?.length > 0 && (
      <Card className="gap-0 border-none p-5">
        <h3 className="text-light-gray mb-3 text-[24px]">Tool Skills</h3>
        <div className="flex flex-wrap gap-2">
          {data.skills.tool.map((item: any) => (
            <span
              key={item.id}
              className="border-border bg-upload-bg group relative flex h-max cursor-pointer items-center justify-center rounded-lg border px-5 py-2 text-[14px] font-medium whitespace-nowrap hover:scale-105"
            >
              {item.name}
            </span>
          ))}
        </div>
      </Card>
    )}
    {data?.languages?.length > 0 && (
      <Card className="gap-0 border-none p-5">
        <div className="flex flex-wrap gap-2">
          <h3 className="text-light-gray mb-3 text-[20px]">Language Expertise</h3>

          {data.languages.map((item: any, i: number) => (
            <span
              key={i}
              className="border-border bg-upload-bg group relative flex h-max cursor-pointer items-center justify-center rounded-lg border px-5 py-2 text-[12px] font-medium whitespace-nowrap hover:scale-105"
            >
              {item.language_name} —{" "}
              {
                languageProficiencyOptions.find(
                  (options) => options.id === Number(item.proficiency),
                )?.label
              }
            </span>
          ))}
        </div>
      </Card>
    )}
    {data?.personal_values?.length > 0 && (
      <Card className="gap-0 border-none p-5">
        <div className="flex flex-wrap gap-2">
          <h3 className="text-light-gray mb-3 text-[20px]">Personal Values</h3>

          {data.personal_values.map((item: any) => (
            <span
              key={item.id}
              className="border-border bg-upload-bg group relative flex h-max cursor-pointer items-center justify-center rounded-lg border px-5 py-2 text-[12px] font-medium whitespace-nowrap hover:scale-105"
            >
              {item.name}
            </span>
          ))}
        </div>
      </Card>
    )}
    {data.hobbies?.length > 0 && (
      <Card className="gap-0 border-none p-5">
        <div className="flex flex-wrap gap-2">
          <h3 className="text-light-gray mb-3 text-[20px]">Hobbies</h3>

          {data.hobbies.map((item: any) => (
            <span
              key={item.id}
              className="border-border bg-upload-bg group relative flex h-max cursor-pointer items-center justify-center rounded-lg border px-5 py-2 text-[12px] font-medium whitespace-nowrap hover:scale-105"
            >
              {item.name}
            </span>
          ))}
        </div>
      </Card>
    )}
  </div>
);

const ProjectSection = ({ data }: { data: any }) => {
  return (
    <div className="flex flex-col gap-4">
      <Card className="gap-0 border-none">
        <h3 className="text-light-gray ml-5 text-[20px]">Projects</h3>
        
        {data?.projects?.length ? (data.projects.map((item: any) => (
          <div
          key={item.uuid}
          className="border-border flex h-max w-full flex-col justify-center gap-2.5 border-b  p-5 text-[12px] font-medium last:border-b-0"
        >
          <div className="flex w-full items-end justify-between">
              <div className="flex items-center gap-2">
                  <div className="text-lg font-semibold">
                    {item.project_name}
                  </div>

                    {item.task_url && (
                      <a
                        href={
                          item.task_url.startsWith("http")
                            ? item.task_url
                            : `https://${item.task_url}`
                        }
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                              <div className="border-border bg-upload-bg cursor-pointer rounded-md border px-2 py-1 font-medium transition hover:scale-105">
                                View Project
                              </div>
                            </a>
                    )}
              </div>
            </div>

            <div className="flex flex-col text-[13px] font-normal">
                  {item.responsibilities && (
                    <div className="flex gap-2">
                      <span className="font-semibold text-black dark:text-white">
                        Responsibility:
                      </span>

                      <span className="text-gray-one">
                        {item.responsibilities}
                      </span>
                    </div>
                  )}

                  {item.task_name && (
                    <div className="flex gap-2">
                      <span className="font-semibold text-black dark:text-white">
                        Task:
                      </span>

                      <span className="text-gray-one">
                        {item.task_name}
                      </span>
                    </div>
                  )}
              </div>
          </div>
          ))
        ) : (
          <p className="px-5 py-4 text-sm text-gray-500">
            No projects found.
          </p>
        )}
        

      </Card>
    </div>
  );
};

const ExperienceSection = ({ data }: { data: ProfileDataType }) => (
  <div className="flex flex-col gap-4">
    <Card className="gap-0 border-none">
      <h3 className="text-light-gray ml-5 text-[20px]">Experiences</h3>
      {data &&
        data?.experiences?.map((items: PublicExperience, index: number) => (
          <div
            key={items.id}
            className="border-border flex h-max w-full flex-col justify-center gap-2.5 border-b  p-5 text-[12px] font-medium last:border-b-0">
            <div className="flex w-full items-end justify-between">
              <div className="flex items-center text-lg font-semibold">
                {items.job_title}
              </div>
            </div>
            <div className="flex flex-col text-[12px] font-normal">
              <div className="flex items-center">
                <div className="text-lg font-semibold">
                  {items.company_name}
                </div>
                -(<div className="font-light">{items.employment_type}</div>)
              </div>
              <div className="flex flex-col gap-0">
                <div className="font-light">
                  <div className="flex gap-1">
                    <div className="font-semibold">
                      Starting date:{" "}
                      <span className="font-light">
                        {new Date(items.start_date).toLocaleDateString()}
                      </span>
                    </div>
                    &
                    <div className="font-semibold">
                      End date:{" "}
                      <span className="font-light">
                        {items.end_date === null
                          ? "Current"
                          : new Date(items.end_date).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="font-semibold">
                  Responsibilities:{" "}
                  <span className="font-light">
                    {items?.responsibilities?.trim()
                      ? items.responsibilities
                      : "N/A"}
                  </span>
                </div>
              </div>
            </div>
          </div>
        ))}
    </Card>
  </div>
);

const EducationSection = ({ data }: { data: any }) => (
  <div className="flex flex-col gap-4">

   
      <Card className="gap-0 border-none">
        <h3 className="text-light-gray ml-5 text-[20px]">Educations</h3>
      {data?.educations?.map((items: any) => (
        <div
          key={items.id}
          className="border-border flex h-max w-full flex-col justify-center gap-2.5 border-b  p-5 text-[12px] font-medium last:border-b-0"
        >
          <div className="flex w-full items-end justify-between">
            <div className="flex items-center text-lg font-semibold">
              {items.degree_name}
            </div>
          </div>
          <div className="flex flex-col text-[13px] font-normal">
            <div className="flex">
              <div className="font-semibold">{items.institute_name}</div>-
              <div className="font-light">{items.location}</div>
            </div>
            <div className="flex flex-col gap-0">
              <div className="font-light">
                Passing Year:{" "}
                <span className="font-semibold">{items.passing_year}</span>
              </div>

              <div className="font-light">
                Major:
                <span className="font-semibold">{items.major}</span>
              </div>
              <div className="font-light">
                Result:
                <span className="font-semibold">{items.result}</span>
              </div>
            </div>
          </div>


        </div>
         ))}
      </Card>
   
  </div>
);

const AchievementsSection = ({ data }: { data: any }) => (
  
  <div className="flex flex-col gap-4">
   
   <Card className="gap-0 border-none">
    <h3 className="text-light-gray ml-5 text-[20px]">Certificates</h3>

    {data?.certificates?.length > 0 ? (
      data.certificates.map((item: PublicCertificate) => {
        const certificateUrl = item.credential_url?.trim();

        const certificateLink = certificateUrl
          ? /^https?:\/\//i.test(certificateUrl)
            ? certificateUrl
            : `https://${certificateUrl}`
          : item.certificate_file
            ? `https://api.weebard.com/storage/${item.certificate_file}`
            : "";

        return (
          <div
            key={item.id}
            className="border-border flex h-max w-full flex-col justify-center gap-2.5 border-b p-5 text-[12px] font-medium last:border-b-0"
          >
            <div className="flex w-full items-end justify-between">
              <div className="flex items-center gap-2">
                <div className="flex items-center text-lg font-semibold">
                  {item.certificate_name}
                </div>

                {certificateLink && (
                  <a
                    href={certificateLink}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <div className="border-border bg-upload-bg cursor-pointer rounded-md border px-2 py-1 font-medium hover:scale-105">
                      View Certificate
                    </div>
                  </a>
                )}
              </div>
            </div>

            <div className="flex flex-col text-[12px] font-light">
              <div className="font-semibold">{item.organization}</div>

              <div>
                Passing Year:{" "}
                <span className="font-semibold">{item.issue_year}</span>
              </div>
            </div>
          </div>
        );
      })
    ) : (
      <div className="p-5 text-center text-sm text-gray-500">
        No certificate records added.
      </div>
    )}
  </Card>
    
   <Card className="gap-0 border-none">
    <h3 className="text-light-gray ml-5 text-[20px]">Awards</h3>

    {data?.awards?.length > 0 ? (
      data.awards.map((item: PublicAward) => {
        const awardUrl = item.award_url?.trim();

        const awardLink = awardUrl
          ? /^https?:\/\//i.test(awardUrl)
            ? awardUrl
            : `https://${awardUrl}`
          : item.award_file
            ? `https://api.weebard.com/storage/${item.award_file}`
            : "";

        return (
          <div
            key={item.uuid}
            className="border-border flex h-max w-full flex-col justify-center gap-2.5 border-b p-5 text-[12px] font-medium last:border-b-0"
          >
            <div className="flex w-full items-end justify-between">
              <div className="flex items-center gap-2">
                <div className="flex items-center text-lg font-semibold">
                  {item.award_name}
                </div>

                {awardLink && (
                  <a
                    href={awardLink}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <div className="border-border bg-upload-bg cursor-pointer rounded-md border px-2 py-1 font-medium hover:scale-105">
                      View Award
                    </div>
                  </a>
                )}
              </div>
            </div>

            <div className="flex flex-col text-[12px] font-light">
              <div className="font-semibold">{item.organization}</div>

              <div>
                Passing Year:{" "}
                <span className="font-semibold">{item.year}</span>
              </div>
            </div>
          </div>
        );
      })
    ) : (
      <div className="p-5 text-center text-sm text-gray-500">
        No award records added.
      </div>
    )}
  </Card>

  </div>
);

const LinksSection = ({ data, linkColumn }: { data: any, linkColumn: Number }) => (
   //const columns = Math.min(data?.links?.length || 1, 4);

  <div className="flex flex-col gap-5">
    <div className="w-full flex flex-col gap-4">
      {data?.links?.length > 0 && (
        // <Card className="gap-0 border-none p-5">
        //   <h3 className="text-light-gray mb-3 text-[20px]">Social Media</h3>
        //   {data.links.map((items: any) => (
        //     <div
        //       key={items.id}
        //       className="border-border mt-3 flex w-full items-stretch border text-[14px] font-medium">
        //       {/* Label */}
        //       <div className="border-border plinkBoxy-4 flex w-42 items-center justify-between gap-2 border-r px-3">
        //         <span className="whitespace-nowrap">
        //           {items.platform || items.label}
        //         </span>

        //         <Image
        //           src={Link}
        //           alt="link"
        //           width={18}
        //           height={18}
        //           className="object-contain"
        //         />
        //       </div>

        //       {/* URL */}
        //       <div className="flex flex-1 items-center truncate px-3 py-2">
        //         {items.url?.startsWith("http")
        //           ? items.url
        //           : `https://${items.url}`}
        //       </div>

        //       {/* Actions */}
        //     </div>
        //   ))}
        // </Card>
        

        <Card className="w-full max-w-[400px] mt-6 border-none p-5">
                 <div className="w-full overflow-hidden rounded-xl border border-gray-300">
                  <ul
                      className="grid border-l border-t border-gray-300"
                      style={{ gridTemplateColumns: `repeat(${linkColumn}, minmax(0, 1fr))` }}
                    >
                      {data?.links?.map((item: any) => (
                        <li
                          key={item.uuid}
                          className="flex justify-center border-r border-b border-gray-300 py-5"
                        >
                          <a
                            href={item.url}
                            target="_blank"
                            rel="noopener noreferrer"
                            title={item.platform}
                            className="text-gray-600 transition-all duration-200 hover:scale-110 hover:text-primary"
                          >
                            {getSocialIcon(item.platform)}
                          </a>
                        </li>
                      ))}
                    </ul>
                </div>
              </Card>

      )}
    </div>
  </div>
);

const ContactSection = ({ data }: { data: any }) => (
  <Card className="gap-0 border-none p-5">
    <h3 className="text-light-gray mb-3 text-[24px]">Contact Details</h3>
    <div className="flex flex-col gap-2 text-[14px]">
      {data?.user?.email && (
        <p>
          Email: <span className="font-medium">{data.user.email}</span>
        </p>
      )}
      {data?.phone && (
        <p>
          Phone: <span className="font-medium">{data.phone}</span>
        </p>
      )}
      {data?.country && (
        <p>
          Country: <span className="font-medium">{data.country}</span>
        </p>
      )}
      {data?.city && (
        <p>
          City: <span className="font-medium">{data.city}</span>
        </p>
      )}
      {data?.present_address && (
        <p>
          Address: <span className="font-medium">{data.present_address}</span>
        </p>
      )}
    </div>
  </Card>
);

const OthersSection = ({ data }: { data: any }) => (
  <div className="flex flex-col gap-4">
    <Card className="gap-0 border-none p-5">
      <h3 className="text-light-gray mb-3 text-[24px]">References</h3>

      {data?.references?.length > 0 &&
        data.references.map((items: any) => (
          <div
            key={items.uuid}
            className="border-border flex h-max w-full flex-col justify-center gap-3 border-b px-5 pt-3 pb-5 text-[14px] font-medium"
          >
            <div className="flex w-full items-center justify-between">
              <div className="flex items-center gap-2">
                <div className="text-lg font-semibold">{items.name}</div>
              </div>
            </div>

            <div className="flex flex-col gap-1 text-[13px] font-light text-gray-600">
              <div className="flex gap-1">
                <span className="font-medium text-gray-800">Occupation:</span>
                {items.occupation}
              </div>

              <div className="flex gap-1">
                <span className="font-medium text-gray-800">Organization:</span>
                {items.organization}
              </div>

              <div className="flex gap-1">
                <span className="font-medium text-gray-800">Mobile:</span>
                {items.mobile || items.phone}
              </div>

              <div className="flex gap-1">
                <span className="font-medium text-gray-800">Relationship:</span>
                {items.relationship}
              </div>
            </div>
          </div>
        ))}
    </Card>
    <Card className="gap-0 border-none p-5">
      <h3 className="text-light-gray mb-3 text-[24px]">Declaration</h3>

      {data?.declaration && (
        <Textarea
          className={`h-80 resize-none border-none py-3 text-lg shadow-none focus-visible:ring-0 focus-visible:ring-offset-0`}
          value={data?.declaration}
          readOnly={true}
        />
      )}
    </Card>
    <Card className="gap-0 border-none p-5">
      <h3 className="text-light-gray mb-3 text-[24px]">Signature</h3>

      <div className="flex h-max w-full flex-col items-center justify-center gap-3 px-5 pt-3 pb-5 text-[14px] font-medium">
        <Image
          src={data.signature}
          alt="signature"
          width={400}
          height={100}
          className="object-contain"
        />{" "}
      </div>
    </Card>
  </div>
);

// ── Section config ───────────────────────────────────────────────────────────

const sections = [
  { id: 1, label: "About", Component: AboutSection },
  { id: 2, label: "Experience", Component: ExperienceSection },
  { id: 3, label: "Education", Component: EducationSection },
  { id: 4, label: "Project", Component: ProjectSection },
  { id: 5, label: "Certificates & Awards", Component: AchievementsSection },
  { id: 6, label: "Links", Component: LinksSection },
  // { id: 7, label: "Contact", Component: ContactSection },
  // { id: 8, label: "Others", Component: OthersSection },
];

// ── Main component ───────────────────────────────────────────────────────────

interface Props {
  data: any; // replace with ProfileDataType when ready
  linkColumn :number;
}

const SharedProfileNavSection = ({ data, linkColumn }: Props) => {
  const [selectedSection, setSelectedSection] = useState(sections[0]);
  const { Component } = selectedSection;

  return (
    <div className="font-poppins flex flex-col gap-2">
      {/* Nav tabs */}
      <div className="flex flex-wrap gap-2">
        {sections.map((section) => {
          const isActive = section.id === selectedSection.id;
          return (
            <div
              key={section.id}
              onClick={() => setSelectedSection(section)}
              className={`${isActive ? "bg-primary-button border-light-gray text-white dark:text-white" : ""}bg-white border-border text-gray-one hover:bg-primary-button hover:border-light-grays cursor-pointer rounded-lg border px-3 py-2.5 text-[12px] font-medium hover:text-white`}
            >
              {section.label}
            </div>
          );
        })}
      </div>

      {/* Active section */}
      <div>
        <Component data={data} linkColumn={linkColumn} />
      </div>
    </div>
  );
};

export default SharedProfileNavSection;
