"use client";

import { useState, useRef, useEffect } from "react";
import Image from "next/image";
import { Loader2 } from "lucide-react";
import { publicProfileApi } from "@/lib/api/public";
import { buildImageUrl } from "@/lib/utils/image";
import type { OrganizationStructure } from "@/types/organizationStructure";

function ProfileNode({
  name,
  tbm,
  title,
  photo,
}: {
  name: string;
  tbm?: string;
  title?: string;
  photo?: string | null;
  isDPO?: boolean;
}) {
  return (
    <div className="flex flex-col items-center text-center z-10 relative min-w-[140px] md:min-w-0">
      <div className="relative w-24 h-24 lg:w-30 lg:h-30 rounded-full border-3 border-[#E67817] bg-white p-1 shadow-md transition-transform duration-300 hover:scale-105">
        <div className="w-full h-full rounded-full overflow-hidden bg-gray-100 flex items-center justify-center">
          <div className="w-full h-full relative rounded-full overflow-hidden">
            {photo ? (
              <Image
                src={buildImageUrl(photo)}
                alt={name}
                fill
                className="object-cover rounded-full"
                sizes="(max-width: 768px) 96px, 120px"
                unoptimized
              />
            ) : (
              <div className="w-full h-full bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center rounded-full">
                <span className="text-gray-400 text-sm">Foto</span>
              </div>
            )}
          </div>
        </div>
      </div>
      <div className="mt-4 max-w-[170px] md:max-w-[200px]">
        <h4 className="text-sm md:text-base font-bold text-main leading-tight">{name}</h4>
        {tbm && (
          <p className="text-xs md:text-sm font-medium text-sec mt-1 uppercase leading-tight">{tbm}</p>
        )}
        {title && (
          <p className="text-sm md:text-base font-bold text-brand mt-1 leading-tight">{title}</p>
        )}
      </div>
    </div>
  );
}

function VLine({ className }: { className?: string }) {
  return <div className={`absolute w-1 bg-[#E67817] ${className}`} />;
}

function HLine({ className }: { className?: string }) {
  return <div className={`absolute h-1 bg-[#E67817] ${className}`} />;
}

export default function OrganizationalStructure() {
  const [isVisible, setIsVisible] = useState(false);
  const [structure, setStructure] = useState<OrganizationStructure[]>([]);
  const [loading, setLoading] = useState(true);
  const sectionRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const dpoMembers = structure.filter(
    (s) =>
      s.position.toLowerCase() === "dpo" ||
      s.position.toLowerCase() === "dewan pengawas organisasi"
  );

  const mainStructure = structure.filter(
    (s) =>
      s.position.toLowerCase() !== "dpo" &&
      s.position.toLowerCase() !== "dewan pengawas organisasi"
  );

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) setIsVisible(true); },
      { threshold: 0.1 }
    );
    if (sectionRef.current) observer.observe(sectionRef.current);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    publicProfileApi
      .getStructure()
      .then((res) => setStructure(res.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const getTbmName = (s: OrganizationStructure) => s.tbm?.tbm ?? "";

  const periodLabel = structure[0]?.period?.name ?? "";

  return (
    <section
      ref={sectionRef}
      className="py-16 px-6 sm:px-6 md:px-20 lg:px-36"
      id="struktur-organisasi"
    >
      <div className="w-full mx-auto">
        <div
          className={`text-center mb-12 md:mb-16 transition-all duration-700 ${isVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
            }`}
        >
          <h2 className="text-3xl md:text-4xl lg:text-5xl font-bold text-main mb-4">
            Struktur <span className="text-brand">Organisasi</span>
          </h2>
          <div className="w-24 h-1 bg-brand mx-auto mb-6"></div>
          <p className="text-lg md:text-xl text-sec max-w-3xl mx-auto">
            {periodLabel ? `Periode ${periodLabel} - ` : ""}Mengenal tim kepemimpinan PTBMMKI
          </p>
        </div>

        {loading ? (
          <div className="flex items-center justify-center h-64 gap-2 text-gray-400">
            <Loader2 className="w-5 h-5 animate-spin" />
            <span>Memuat struktur organisasi...</span>
          </div>
        ) : structure.length === 0 ? (
          <div className="flex items-center justify-center h-32 text-gray-400">
            <p>Belum ada data struktur organisasi</p>
          </div>
        ) : (
          <div className="relative">
            <div
              ref={containerRef}
              className="overflow-x-auto lg:overflow-x-visible pb-8"
              style={{ scrollbarWidth: "thin", scrollbarColor: "#E67817 #f1f1f1" }}
            >
              <div className="min-w-[1200px] lg:min-w-0 relative pt-2 md:pt-0">
                <div className="relative md:mb-6 h-64">
                  {mainStructure[0] && (
                    <div className="absolute left-[43%] md:left-[41.5%] lg:left-[44%] top-0">
                      <ProfileNode
                        name={mainStructure[0].name}
                        tbm={getTbmName(mainStructure[0])}
                        title={mainStructure[0].position}
                        photo={mainStructure[0].photo}
                      />
                    </div>
                  )}
                  {dpoMembers.map((dpo) => (
                    <div
                      key={dpo.id}
                      className="absolute right-[15%] md:right-[10%] lg:right-[15%] top-0"
                    >
                      <ProfileNode
                        name={dpo.name}
                        tbm={getTbmName(dpo)}
                        title={dpo.position}
                        photo={dpo.photo}   
                        isDPO
                      />
                    </div>
                  ))}
                </div>

                <div className="relative pt-8 lg:pt-12">
                  <HLine className="top-0 left-[7.8%] right-[7.8%]" />
                  <div className="grid grid-cols-6 gap-4 lg:gap-6">
                    {mainStructure.slice(1, 7).map((s, i) => (
                      <div key={s.id} className="relative flex justify-center">
                        <VLine className="-top-8 md:-top-12 h-8 md:h-12" />
                        <ProfileNode
                          name={s.name}
                          tbm={getTbmName(s)}
                          title={s.position}
                          photo={s.photo}
                        />
                      </div>
                    ))}
                  </div>
                  <VLine className="left-1/2 -top-10 md:-top-12 h-[720px] md:h-[760px] -translate-x-1/2" />
                </div>

                <div className="grid grid-cols-2 gap-8 md:gap-12 mt-16 md:mt-20 relative">
                  <div className="relative pt-8 md:pt-12">
                    <HLine className="-top-10 left-[15.5%] right-[50%]" />
                    <HLine className="top-0 left-[50%] right-[15.5%]" />
                    <VLine className="left-[15.2%] -top-15 h-[80px] lg:h-[100px] -translate-x-1/2" />
                    <VLine className="left-[50%] -top-15 h-[24px] -translate-x-1/2" />
                    <VLine className="left-[85.5%] -top-15 h-[24px] -translate-x-1/2" />
                    <HLine className="-top-10 left-[67.5%] right-[14.5%]" />
                    <VLine className="left-[67.5%] -top-10 h-[40px] -translate-x-1/2" />
                    <div className="grid grid-cols-3 gap-6 md:gap-8">
                      {mainStructure.slice(7, 10).map((s) => (
                        <div key={s.id} className="relative flex justify-center">
                          <VLine className="-top-8 md:-top-12 h-8 md:h-12" />
                          <ProfileNode
                            name={s.name}
                            tbm={getTbmName(s)}
                            title={s.position}
                            photo={s.photo}
                          />
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="relative pt-8 md:pt-12">
                    <HLine className="top-0 left-[10.5%] right-[37%]" />
                    <HLine className="-top-10 left-[14%] right-[63%]" />
                    <VLine className="left-[36.8%] -top-10 h-[40px] -translate-x-1/2" />
                    <VLine className="left-[14%] -top-15 h-[24px] -translate-x-1/2" />
                    <HLine className="-top-10 left-[50%] right-[10.1%]" />
                    <VLine className="left-[50%] -top-15 h-[24px] -translate-x-1/2" />
                    <VLine className="left-[84%] -top-15 h-[24px] -translate-x-1/2" />
                    <VLine className="left-[89.5%] -top-10 h-[40px] -translate-x-1/2" />
                    <div className="grid grid-cols-4 gap-8 md:gap-6">
                      {mainStructure.slice(10, 14).map((s) => (
                        <div key={s.id} className="relative flex justify-center">
                          <VLine className="-top-8 md:-top-12 h-8 md:h-12" />
                          <ProfileNode
                            name={s.name}
                            tbm={getTbmName(s)}
                            title={s.position}
                            photo={s.photo}
                          />
                        </div>
                      ))}
                    </div>
                  </div>
                </div>

                <div className="relative mt-16 md:mt-24 pt-8 md:pt-12">
                  <HLine className="top-0 left-[9.5%] right-[9.5%]" />
                  <div className="grid grid-cols-5 gap-4 md:gap-6">
                    {mainStructure.slice(14, 19).map((s) => (
                      <div key={s.id} className="relative flex justify-center">
                        <VLine className="-top-8 md:-top-12 h-8 md:h-12" />
                        <ProfileNode
                          name={s.name}
                          tbm={getTbmName(s)}
                          title={s.position}
                          photo={s.photo}
                        />
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="md:hidden flex justify-center mt-6">
              <div className="flex items-center space-x-2">
                <div className="w-2 h-2 rounded-full bg-gray-300"></div>
                <div className="text-sm text-sec">Scroll untuk melihat →</div>
                <div className="w-2 h-2 rounded-full bg-gray-300"></div>
              </div>
            </div>
          </div>
        )}
      </div>

      <style jsx>{`
        .overflow-x-auto::-webkit-scrollbar { height: 6px; }
        .overflow-x-auto::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 10px; }
        .overflow-x-auto::-webkit-scrollbar-thumb { background: #e67817; border-radius: 10px; }
        .overflow-x-auto::-webkit-scrollbar-thumb:hover { background: #d46a15; }
      `}</style>
    </section>
  );
}