"use client";

import React, { useState, useRef, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { 
  ChevronLeft, 
  ChevronRight, 
  Sparkles, 
  Github, 
  Linkedin, 
  Mail, 
  ExternalLink, 
  CheckCircle2, 
  Play, 
  Pause,
  ArrowUpRight,
  Briefcase
} from "lucide-react";
import { SectionCorners } from "@/components/ui/SectionCorner";
import { useAppStore } from "@/lib/store";
import { TeamMemberItem } from "@/types";

export interface Showcase8Props {
  title?: string;
  subtitle?: string;
  badge?: string;
  items?: TeamMemberItem[];
}

export function Showcase8({
  title = "Engineering Leadership & Specialist Pods",
  subtitle = "Directly collaborated by specialized technical leads with deep domain expertise in Next.js 14, Flutter, offline POS runtimes, and distributed databases.",
  badge = "// 05. SCROLL-SNAP EDITORIAL SHOWCASE",
  items,
}: Showcase8Props) {
  const { teamMembers } = useAppStore();
  const teamList = items || teamMembers || [];

  const [selectedDept, setSelectedDept] = useState<string>("All");
  const [currentIndex, setCurrentIndex] = useState<number>(0);
  const [isAutoPlaying, setIsAutoPlaying] = useState<boolean>(false);
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const filteredTeam = selectedDept === "All"
    ? teamList
    : teamList.filter((m) => m.department.toLowerCase().includes(selectedDept.toLowerCase()));

  const total = filteredTeam.length || 1;
  const progressPercent = Math.min(100, Math.round(((currentIndex + 1) / total) * 100));

  const departments = [
    "All",
    "Executive",
    "Design",
    "Mobile",
    "Frontend",
    "Growth"
  ];

  const handleScroll = () => {
    if (!scrollContainerRef.current) return;
    const container = scrollContainerRef.current;
    const scrollLeft = container.scrollLeft;
    const itemWidth = container.firstElementChild ? (container.firstElementChild as HTMLElement).offsetWidth + 24 : container.clientWidth;
    const newIdx = Math.round(scrollLeft / itemWidth);
    if (newIdx !== currentIndex && newIdx >= 0 && newIdx < total) {
      setCurrentIndex(newIdx);
    }
  };

  const scrollToIndex = (idx: number) => {
    if (!scrollContainerRef.current) return;
    const clamped = Math.max(0, Math.min(idx, total - 1));
    const container = scrollContainerRef.current;
    const itemWidth = container.firstElementChild ? (container.firstElementChild as HTMLElement).offsetWidth + 24 : container.clientWidth;
    container.scrollTo({
      left: clamped * itemWidth,
      behavior: "smooth",
    });
    setCurrentIndex(clamped);
  };

  const handlePrev = () => scrollToIndex(currentIndex - 1);
  const handleNext = () => scrollToIndex(currentIndex + 1);

  // Auto play effect
  useEffect(() => {
    if (!isAutoPlaying) return;
    const interval = setInterval(() => {
      setCurrentIndex((prev) => {
        const next = prev >= total - 1 ? 0 : prev + 1;
        scrollToIndex(next);
        return next;
      });
    }, 4000);
    return () => clearInterval(interval);
  }, [isAutoPlaying, total]);

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "ArrowLeft") handlePrev();
      if (e.key === "ArrowRight") handleNext();
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [currentIndex, total]);

  return (
    <section className="relative w-full border-b border-border bg-card/40 py-16 sm:py-24 overflow-hidden font-sans">
      <SectionCorners />

      <div className="mx-auto max-w-[1440px] px-6 sm:px-10 lg:px-14">
        {/* Top Header & Department Filters */}
        <div className="flex flex-col lg:flex-row lg:items-end justify-between gap-6 mb-12">
          <div className="space-y-3 max-w-2xl">
            <div className="inline-flex items-center gap-2 rounded-full border border-border bg-muted px-4 py-1.5 text-xs font-mono text-foreground shadow-xs">
              <span className="h-2 w-2 rounded-full bg-[#024d37] animate-pulse" />
              <span className="text-[#024d37] font-semibold">{badge}</span>
            </div>

            <h2 className="text-3xl sm:text-5xl font-semibold tracking-tight text-foreground font-sans">
              {title}
            </h2>

            <p className="text-xs sm:text-sm text-muted-foreground leading-relaxed">
              {subtitle}
            </p>
          </div>

          {/* Department Tabs */}
          <div className="flex flex-wrap items-center gap-2 font-mono text-xs">
            {departments.map((dept) => (
              <button
                key={dept}
                onClick={() => {
                  setSelectedDept(dept);
                  setCurrentIndex(0);
                  if (scrollContainerRef.current) {
                    scrollContainerRef.current.scrollTo({ left: 0, behavior: "smooth" });
                  }
                }}
                className={`rounded-full px-4 py-2 transition-all cursor-pointer ${
                  selectedDept === dept
                    ? "bg-[#024d37] text-white font-bold shadow-md shadow-[#024d37]/20"
                    : "border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted"
                }`}
              >
                {dept}
              </button>
            ))}
          </div>
        </div>

        {/* Scroll-Snap Carousel Container (React Bits Pro Editorial Cards) */}
        <div
          ref={scrollContainerRef}
          onScroll={handleScroll}
          className="flex overflow-x-auto snap-x snap-mandatory no-scrollbar gap-6 pb-6 cursor-grab active:cursor-grabbing"
          style={{ scrollSnapType: "x mandatory" }}
        >
          {filteredTeam.map((member, idx) => (
            <article
              key={member.id || idx}
              className="min-w-[88%] sm:min-w-[460px] lg:min-w-[500px] snap-center shrink-0 rounded-3xl border border-border/80 bg-card p-6 sm:p-8 shadow-xl hover:border-[#024d37]/60 transition-all duration-300 relative group flex flex-col justify-between overflow-hidden"
            >
              {/* Card Top Metadata */}
              <div className="flex items-center justify-between font-mono text-xs border-b border-border pb-4 mb-6">
                <span className="text-[#024d37] font-bold tracking-wider">
                  // EDITORIAL #{String(idx + 1).padStart(2, "0")} OF {String(total).padStart(2, "0")}
                </span>
                <span className="rounded-full bg-muted border border-border px-3 py-1 text-[11px] text-foreground font-semibold">
                  {member.department}
                </span>
              </div>

              {/* Portrait & Core Info Split */}
              <div className="grid grid-cols-1 sm:grid-cols-12 gap-6 items-center">
                {/* Portrait */}
                <div className="sm:col-span-5 relative">
                  <div className="relative aspect-[3/4] w-full rounded-2xl overflow-hidden bg-muted border border-border shadow-md group-hover:shadow-xl transition-shadow">
                    <Image
                      src={member.image || "/assets/team/irfan.jpg"}
                      alt={member.name}
                      fill
                      className="object-cover object-top transition-transform duration-700 group-hover:scale-105"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-transparent" />
                    
                    {member.featured && (
                      <div className="absolute top-2.5 right-2.5 rounded-full bg-[#024d37] px-2.5 py-0.5 font-mono text-[9px] font-bold uppercase tracking-wider text-emerald-200 shadow-sm">
                        Pod Lead
                      </div>
                    )}

                    <div className="absolute bottom-3 left-3 right-3 text-white font-mono text-[10px] flex items-center gap-1">
                      <CheckCircle2 className="h-3 w-3 text-emerald-400 shrink-0" />
                      <span className="truncate">Active Core Architect</span>
                    </div>
                  </div>
                </div>

                {/* Info Text */}
                <div className="sm:col-span-7 space-y-3">
                  <div>
                    <h3 className="text-2xl font-bold text-foreground font-sans group-hover:text-[#024d37] transition-colors">
                      {member.name}
                    </h3>
                    <p className="font-mono text-xs text-[#024d37] font-semibold mt-0.5">
                      {member.role}
                    </p>
                  </div>

                  <p className="text-xs text-muted-foreground leading-relaxed line-clamp-4">
                    {member.bio}
                  </p>

                  {/* Tech stack chips */}
                  <div className="pt-2">
                    <span className="font-mono text-[10px] text-muted-foreground uppercase tracking-wider block mb-1.5">
                      Core Stack:
                    </span>
                    <div className="flex flex-wrap gap-1 font-mono text-[10px]">
                      {member.tech_stack.slice(0, 4).map((tech, i) => (
                        <span
                          key={i}
                          className="rounded-full border border-border bg-muted/80 px-2.5 py-0.5 text-foreground font-medium"
                        >
                          {tech}
                        </span>
                      ))}
                    </div>
                  </div>
                </div>
              </div>

              {/* Card Footer Action Bar */}
              <div className="mt-6 pt-4 border-t border-border flex items-center justify-between font-mono text-xs">
                <div className="flex items-center gap-2">
                  {member.github && (
                    <a
                      href={member.github}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="h-8 w-8 rounded-xl border border-border bg-muted flex items-center justify-center text-muted-foreground hover:text-foreground hover:border-[#024d37] transition-all"
                      aria-label="GitHub Profile"
                    >
                      <Github className="h-3.5 w-3.5" />
                    </a>
                  )}
                  {member.linkedin && (
                    <a
                      href={member.linkedin}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="h-8 w-8 rounded-xl border border-border bg-muted flex items-center justify-center text-muted-foreground hover:text-[#0077b5] hover:border-[#0077b5] transition-all"
                      aria-label="LinkedIn Profile"
                    >
                      <Linkedin className="h-3.5 w-3.5" />
                    </a>
                  )}
                </div>

                <Link
                  href="/contact"
                  className="inline-flex items-center gap-1.5 rounded-full bg-[#024d37] px-4 py-2 font-mono text-xs font-bold text-white hover:bg-[#036549] transition-all shadow-sm"
                >
                  <span>Book Consultation</span>
                  <ArrowUpRight className="h-3.5 w-3.5" />
                </Link>
              </div>
            </article>
          ))}
        </div>

        {/* Bottom Editorial Controls: Progress Rail, Counter & Tactile Arrows */}
        <div className="mt-8 pt-6 border-t border-border flex flex-col sm:flex-row items-center justify-between gap-6 font-mono text-xs">
          {/* Counter & Clickable Progress Segments */}
          <div className="flex items-center gap-4 w-full sm:w-auto">
            <div className="flex items-center gap-2 font-bold text-foreground">
              <span className="text-[#024d37] text-base">{String(currentIndex + 1).padStart(2, "0")}</span>
              <span className="text-muted-foreground">/</span>
              <span className="text-muted-foreground">{String(total).padStart(2, "0")}</span>
            </div>

            {/* Clickable Progress Rail Bar */}
            <div className="relative h-2 w-full sm:w-64 rounded-full bg-muted overflow-hidden flex cursor-pointer">
              <div
                className="h-full bg-[#024d37] transition-all duration-300 ease-out rounded-full"
                style={{ width: `${progressPercent}%` }}
              />
            </div>
          </div>

          {/* Navigation Controls: Play/Pause, Prev & Next */}
          <div className="flex items-center gap-3">
            <button
              onClick={() => setIsAutoPlaying(!isAutoPlaying)}
              title={isAutoPlaying ? "Pause Auto-Slide" : "Play Auto-Slide"}
              className="h-10 px-3 rounded-full border border-border bg-card flex items-center gap-1.5 text-muted-foreground hover:text-foreground hover:border-[#024d37] transition-all cursor-pointer shadow-xs"
            >
              {isAutoPlaying ? (
                <>
                  <Pause className="h-3.5 w-3.5 text-[#024d37]" />
                  <span className="text-[11px]">Auto ON</span>
                </>
              ) : (
                <>
                  <Play className="h-3.5 w-3.5 text-muted-foreground" />
                  <span className="text-[11px]">Auto</span>
                </>
              )}
            </button>

            <button
              onClick={handlePrev}
              disabled={currentIndex === 0}
              aria-label="Previous Slide"
              className="h-10 w-10 rounded-full border border-border bg-card flex items-center justify-center text-foreground hover:border-[#024d37] hover:bg-muted transition-all disabled:opacity-30 disabled:pointer-events-none cursor-pointer shadow-xs"
            >
              <ChevronLeft className="h-5 w-5" />
            </button>

            <button
              onClick={handleNext}
              disabled={currentIndex >= total - 1}
              aria-label="Next Slide"
              className="h-10 w-10 rounded-full bg-[#024d37] text-white flex items-center justify-center hover:bg-[#036549] transition-all disabled:opacity-30 disabled:pointer-events-none cursor-pointer shadow-md shadow-[#024d37]/25"
            >
              <ChevronRight className="h-5 w-5" />
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}
