"use client";
import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Link from "next/link";
import { ChevronRight, ArrowRight, Calendar, Users, Briefcase, Award, Globe, Heart, ShieldCheck, Mail, Send, ChevronDown } from "lucide-react";
import { SpotlightCard } from "../SpotlightCard";

export interface TimelineMilestone {
  year: string;
  title: string;
  desc: string;
}

export interface TeamMember {
  name: string;
  role: string;
  bio: string;
  image?: string;
  department: string;
}

export interface JobOpening {
  title: string;
  department: string;
  location: string;
  type: string;
  description: string;
}

export interface PressRelease {
  title: string;
  source: string;
  date: string;
  summary: string;
  link?: string;
}

export interface PartnerItem {
  name: string;
  description: string;
  category: string;
  tier: string;
}

export interface CompanyStat {
  value: string;
  label: string;
}

interface CompanyLayoutProps {
  heroBadge: string;
  title: string;
  tagline: string;
  breadcrumb: string;
  intro: string;
  stats?: CompanyStat[];
  timeline?: TimelineMilestone[];
  team?: TeamMember[];
  jobs?: JobOpening[];
  press?: PressRelease[];
  partners?: PartnerItem[];
}

export default function CompanyLayout({
  heroBadge,
  title,
  tagline,
  breadcrumb,
  intro,
  stats = [],
  timeline = [],
  team = [],
  jobs = [],
  press = [],
  partners = [],
}: CompanyLayoutProps) {
  const [selectedDept, setSelectedDept] = useState("all");
  const [appliedJobIdx, setAppliedJobIdx] = useState<number | null>(null);
  const [activeAccordion, setActiveAccordion] = useState<number | null>(null);
  const [careersEmail, setCareersEmail] = useState("");
  const [newsletterSubscribed, setNewsletterSubscribed] = useState(false);

  const teamDepartments = ["all", ...Array.from(new Set(team.map((t) => t.department.toLowerCase())))];
  const filteredTeam = selectedDept === "all" ? team : team.filter((t) => t.department.toLowerCase() === selectedDept);

  const handleApply = (idx: number) => {
    setAppliedJobIdx(idx);
    setTimeout(() => {
      setAppliedJobIdx(null);
    }, 2000);
  };

  const handleNewsletterSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (careersEmail) {
      setNewsletterSubscribed(true);
      setTimeout(() => {
        setNewsletterSubscribed(false);
        setCareersEmail("");
      }, 3000);
    }
  };

  return (
    <div className="relative min-h-screen overflow-hidden bg-orbit-bg-deep orbit-grid-mesh">
      {/* Background Glows */}
      <div className="absolute top-[-10%] left-[-10%] h-[500px] w-[500px] rounded-full bg-orbit-blue/10 blur-[120px]" />
      <div className="absolute bottom-[10%] right-[-10%] h-[600px] w-[600px] rounded-full bg-orbit-purple/8 blur-[130px]" />

      <main className="mx-auto max-w-7xl px-4 py-8 md:px-8">
        {/* Breadcrumb */}
        <div className="mb-6 flex items-center gap-2 text-xs font-mono text-slate-500">
          <Link href="/" className="hover:text-orbit-cyan">Home</Link>
          <ChevronRight className="h-3 w-3" />
          <span className="hover:text-orbit-cyan">Company</span>
          <ChevronRight className="h-3 w-3" />
          <span className="text-slate-600 dark:text-slate-300">{breadcrumb}</span>
        </div>

        {/* Hero Section */}
        <section className="mb-16 grid gap-8 lg:grid-cols-12 lg:items-center">
          <div className="lg:col-span-8">
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
              className="space-y-4"
            >
              <div className="inline-flex rounded-full border border-orbit-cyan/20 bg-orbit-cyan/5 px-3 py-1 font-mono text-[10px] font-bold uppercase tracking-widest text-orbit-cyan">
                {heroBadge}
              </div>
              <h1 className="text-4xl font-extrabold tracking-tight text-slate-900 dark:text-white sm:text-5xl md:text-6xl">
                {title} <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">{tagline}</span>
              </h1>
              <p className="max-w-2xl text-sm leading-relaxed text-slate-600 dark:text-slate-400 sm:text-base">
                {intro}
              </p>
            </motion.div>
          </div>

          {/* Glowing Seal / Decorative Badge */}
          <div className="lg:col-span-4 flex justify-center lg:justify-end">
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.7, delay: 0.2 }}
              className="relative overflow-hidden rounded-full border border-orbit-cyan/20 bg-orbit-bg-primary/40 p-8 shadow-2xl backdrop-blur-md flex items-center justify-center w-48 h-48 animate-orbit-pulse"
            >
              <div className="absolute inset-0 bg-gradient-to-tr from-orbit-cyan/5 via-orbit-purple/5 to-transparent" />
              <div className="flex flex-col items-center text-center space-y-1 z-10">
                <Globe className="h-10 w-10 text-orbit-cyan animate-pulse mb-1" />
                <span className="font-mono text-[9px] font-extrabold text-slate-500 uppercase tracking-wider">Orbit Core</span>
                <span className="font-mono text-[10px] font-black text-slate-800 dark:text-white">EST. 2014</span>
              </div>
            </motion.div>
          </div>
        </section>

        {/* Dynamic Metric Tiles */}
        {stats.length > 0 && (
          <section className="mb-16 grid grid-cols-2 gap-4 md:grid-cols-4">
            {stats.map((stat, idx) => (
              <motion.div
                key={stat.label}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.5, delay: idx * 0.1 }}
              >
                <SpotlightCard className="flex flex-col justify-center rounded-2xl p-6 text-center">
                  <span className="text-3xl font-black text-orbit-cyan tracking-tight">{stat.value}</span>
                  <span className="mt-1 font-mono text-xs text-slate-500 dark:text-slate-400 font-semibold">{stat.label}</span>
                </SpotlightCard>
              </motion.div>
            ))}
          </section>
        )}

        {/* Section Divider */}
        {stats.length > 0 && (
          <div className="orbit-speed-line my-12 h-[1px] bg-gradient-to-r from-transparent via-orbit-cyan/20 to-transparent" />
        )}

        {/* History / Timeline Section */}
        {timeline.length > 0 && (
          <section className="mb-16">
            <div className="mb-8 text-center">
              <h2 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white md:text-3xl">
                Operational <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">Milestones</span>
              </h2>
              <p className="mx-auto mt-2 max-w-xl text-xs text-slate-500">
                Our history of pioneering energy telemetry, Edge compute gateways, and multivariate industrial AI models.
              </p>
            </div>

            <div className="relative border-l border-orbit-border ml-4 md:ml-32 space-y-8">
              {timeline.map((item, idx) => (
                <motion.div
                  key={item.year}
                  initial={{ opacity: 0, x: -30 }}
                  whileInView={{ opacity: 1, x: 0 }}
                  viewport={{ once: true }}
                  transition={{ duration: 0.5, delay: idx * 0.1 }}
                  className="relative pl-8 md:pl-12"
                >
                  {/* Point node */}
                  <span className="absolute -left-2.5 top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-orbit-bg-deep border-2 border-orbit-cyan shadow-[0_0_8px_rgba(0,212,255,0.6)]">
                    <span className="h-1.5 w-1.5 rounded-full bg-orbit-cyan" />
                  </span>
                  
                  {/* Year Tag */}
                  <div className="absolute left-[-110px] top-1 hidden md:block w-20 text-right font-mono text-sm font-bold text-orbit-cyan">
                    {item.year}
                  </div>

                  <div className="rounded-3xl border border-orbit-border bg-orbit-bg-secondary/40 p-6 backdrop-blur-sm shadow-xl">
                    <span className="inline-block md:hidden font-mono text-xs font-bold text-orbit-cyan mb-1">{item.year}</span>
                    <h3 className="text-base font-bold text-slate-900 dark:text-white mb-2">{item.title}</h3>
                    <p className="text-xs leading-relaxed text-slate-655 dark:text-slate-400">{item.desc}</p>
                  </div>
                </motion.div>
              ))}
            </div>
          </section>
        )}

        {/* Leadership Team Section */}
        {team.length > 0 && (
          <section className="mb-16">
            <div className="mb-8 flex flex-col md:flex-row md:items-end md:justify-between border-b border-orbit-border pb-4">
              <div>
                <h2 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white sm:text-3xl">
                  Executive <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">Leadership</span>
                </h2>
                <p className="text-xs text-slate-500 mt-1">
                  Meet the elite system architects and energy engineering directors leading Orbit.
                </p>
              </div>

              {/* Department Filters */}
              <div className="mt-4 flex flex-wrap gap-2 md:mt-0">
                {teamDepartments.map((dept) => (
                  <button
                    key={dept}
                    onClick={() => setSelectedDept(dept)}
                    className={`rounded-full px-3 py-1 font-mono text-[9px] font-bold uppercase tracking-wider transition-colors ${
                      selectedDept === dept
                        ? "bg-orbit-cyan/20 border border-orbit-cyan/30 text-orbit-cyan"
                        : "border border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-900 dark:text-white"
                    }`}
                  >
                    {dept}
                  </button>
                ))}
              </div>
            </div>

            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              <AnimatePresence mode="popLayout">
                {filteredTeam.map((member, idx) => (
                  <motion.div
                    layout
                    key={member.name}
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 0.95 }}
                    transition={{ duration: 0.3 }}
                  >
                    <SpotlightCard className="rounded-3xl p-6 h-full flex flex-col justify-between">
                      <div>
                        {/* Avatar placeholder */}
                        <div className="mb-4 h-16 w-16 rounded-2xl border border-orbit-border bg-orbit-bg-deep flex items-center justify-center">
                          <Users className="h-8 w-8 text-orbit-purple" />
                        </div>
                        <h3 className="text-base font-bold text-slate-900 dark:text-white">{member.name}</h3>
                        <span className="font-mono text-[10px] font-bold text-orbit-cyan uppercase tracking-widest block mb-3">
                          {member.role}
                        </span>
                        <p className="text-xs leading-relaxed text-slate-600 dark:text-slate-400">{member.bio}</p>
                      </div>
                      <div className="mt-6 border-t border-orbit-border pt-4 flex gap-3 text-slate-500">
                        <Link href="/support" className="hover:text-orbit-cyan">
                          <Mail className="h-4 w-4" />
                        </Link>
                      </div>
                    </SpotlightCard>
                  </motion.div>
                ))}
              </AnimatePresence>
            </div>
          </section>
        )}

        {/* Job Openings / Careers Section */}
        {jobs.length > 0 && (
          <section className="mb-16">
            <div className="mb-8 border-b border-orbit-border pb-4">
              <h2 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white sm:text-3xl">
                Current <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">Opportunities</span>
              </h2>
              <p className="text-xs text-slate-500 mt-1">
                Help build the future of autonomous, zero-carbon Industry 4.0 automation systems.
              </p>
            </div>

            <div className="space-y-4">
              {jobs.map((job, idx) => {
                const isOpen = activeAccordion === idx;
                return (
                  <div
                    key={job.title}
                    className="overflow-hidden rounded-2xl border border-orbit-border bg-orbit-bg-secondary/40 backdrop-blur-sm"
                  >
                    <button
                      onClick={() => setActiveAccordion(isOpen ? null : idx)}
                      className="flex w-full flex-col sm:flex-row sm:items-center justify-between p-6 text-left text-slate-900 dark:text-white hover:text-orbit-cyan transition-colors gap-4"
                    >
                      <div>
                        <h3 className="text-sm font-bold">{job.title}</h3>
                        <div className="mt-1 flex flex-wrap items-center gap-3 font-mono text-[9px] font-bold text-slate-500 uppercase tracking-widest">
                          <span>{job.department}</span>
                          <span>·</span>
                          <span>{job.location}</span>
                          <span>·</span>
                          <span>{job.type}</span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-[9px] font-bold tracking-wider text-orbit-cyan sm:block hidden">VIEW DETAILS</span>
                        <ChevronDown className={`h-4.5 w-4.5 shrink-0 transition-transform duration-300 ${isOpen ? "rotate-180 text-orbit-cyan" : "text-slate-500"}`} />
                      </div>
                    </button>

                    <AnimatePresence initial={false}>
                      {isOpen && (
                        <motion.div
                          initial={{ height: 0 }}
                          animate={{ height: "auto" }}
                          exit={{ height: 0 }}
                          transition={{ duration: 0.3, ease: "easeInOut" }}
                        >
                          <div className="border-t border-orbit-border bg-orbit-bg-deep/40 p-6 space-y-4">
                            <p className="text-xs leading-relaxed text-slate-600 dark:text-slate-400">{job.description}</p>
                            <div className="flex flex-col sm:flex-row gap-4 pt-4 border-t border-slate-900 justify-between items-start sm:items-center">
                              <span className="font-mono text-[9px] text-slate-500">Requirements: Masters in Automation, Telecommunications, or similar. 3+ years experience.</span>
                              <button
                                onClick={() => handleApply(idx)}
                                disabled={appliedJobIdx !== null}
                                className={`h-9 px-6 rounded-xl font-mono text-xs font-bold transition-all flex items-center gap-1.5 ${
                                  appliedJobIdx === idx
                                    ? "bg-orbit-green/20 border border-orbit-green/30 text-orbit-green"
                                    : "bg-orbit-cyan text-orbit-bg-deep hover:bg-orbit-cyan/85"
                                }`}
                              >
                                {appliedJobIdx === idx ? "APPLICATION SUBMITTED" : "SUBMIT CV / RESUME"}
                              </button>
                            </div>
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                );
              })}
            </div>

            {/* Careers Newsletter CTA */}
            <div className="mt-12 rounded-3xl border border-orbit-cyan/15 bg-orbit-cyan/5 p-8 relative overflow-hidden">
              <div className="absolute top-0 right-0 w-32 h-32 bg-orbit-cyan/10 blur-2xl rounded-full" />
              <div className="max-w-2xl">
                <h3 className="text-lg font-bold text-slate-900 dark:text-white mb-2">Don&apos;t see the right position?</h3>
                <p className="text-xs leading-relaxed text-slate-600 dark:text-slate-400 mb-6">
                  Subscribe to our recruitment notifications. We are expanding our team of edge engineers, sales developers, and IIoT platform coders.
                </p>
                <form onSubmit={handleNewsletterSubmit} className="flex flex-col sm:flex-row gap-3 max-w-md">
                  <input
                    type="email"
                    required
                    value={careersEmail}
                    onChange={(e) => setCareersEmail(e.target.value)}
                    placeholder="Enter email address..."
                    className="flex-1 rounded-xl border border-orbit-border bg-orbit-bg-deep px-4 py-2.5 text-xs font-mono text-slate-800 dark:text-slate-200 outline-none focus:border-orbit-cyan"
                  />
                  <button
                    type="submit"
                    className="h-10 rounded-xl bg-gradient-to-r from-orbit-cyan to-orbit-purple px-6 text-xs font-bold font-mono text-white flex items-center justify-center gap-2"
                  >
                    {newsletterSubscribed ? "SUBSCRIBED" : (
                      <>
                        <span>JOIN TALENT POOL</span>
                        <Send className="h-3 w-3" />
                      </>
                    )}
                  </button>
                </form>
              </div>
            </div>
          </section>
        )}

        {/* Press Releases / Awards Grid */}
        {press.length > 0 && (
          <section className="mb-16">
            <div className="mb-8 border-b border-orbit-border pb-4">
              <h2 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white sm:text-3xl">
                Press & <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">Recognitions</span>
              </h2>
              <p className="text-xs text-slate-500 mt-1">
                Announcements, press mentions, and international corporate engineering accolades.
              </p>
            </div>

            <div className="grid gap-6 md:grid-cols-2">
              {press.map((release, i) => (
                <SpotlightCard key={release.title} className="rounded-3xl p-6 flex flex-col justify-between h-full">
                  <div className="space-y-3">
                    <div className="flex justify-between items-center font-mono text-[9px] font-bold text-slate-500 uppercase tracking-widest">
                      <span>{release.source}</span>
                      <span className="flex items-center gap-1">
                        <Calendar className="h-3 w-3" />
                        {release.date}
                      </span>
                    </div>
                    <h3 className="text-sm font-bold text-slate-900 dark:text-white leading-snug hover:text-orbit-cyan transition-colors">
                      {release.title}
                    </h3>
                    <p className="text-xs leading-relaxed text-slate-600 dark:text-slate-400">{release.summary}</p>
                  </div>
                  <div className="mt-6 border-t border-orbit-border pt-4">
                    <Link
                      href={release.link || "#"}
                      className="inline-flex items-center gap-1.5 font-mono text-xs text-orbit-cyan hover:underline"
                    >
                      Read Full Article <ArrowRight className="h-3.5 w-3.5" />
                    </Link>
                  </div>
                </SpotlightCard>
              ))}
            </div>
          </section>
        )}

        {/* Partners Section */}
        {partners.length > 0 && (
          <section className="mb-16">
            <div className="mb-8 text-center">
              <h2 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white md:text-3xl">
                Partner <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">Ecosystem</span>
              </h2>
              <p className="mx-auto mt-2 max-w-xl text-xs text-slate-500">
                Strategic integrations and certified system partners deploying Orbit solutions worldwide.
              </p>
            </div>

            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {partners.map((partner, i) => (
                <SpotlightCard key={partner.name} className="rounded-3xl p-6 h-full flex flex-col justify-between">
                  <div>
                    <div className="flex justify-between items-start mb-4">
                      <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-orbit-cyan/10 border border-orbit-cyan/20">
                        <Award className="h-5 w-5 text-orbit-cyan" />
                      </div>
                      <span className="rounded-full bg-orbit-cyan/10 border border-orbit-cyan/20 px-2 py-0.5 font-mono text-[8px] font-bold text-orbit-cyan">
                        {partner.tier}
                      </span>
                    </div>
                    <h3 className="text-base font-bold text-slate-900 dark:text-white mb-2">{partner.name}</h3>
                    <p className="text-xs leading-relaxed text-slate-600 dark:text-slate-400 mb-4">{partner.description}</p>
                  </div>
                  <div className="border-t border-orbit-border pt-4 font-mono text-[9px] font-bold text-slate-500 uppercase tracking-widest">
                    Category: {partner.category}
                  </div>
                </SpotlightCard>
              ))}
            </div>
          </section>
        )}
      </main>
    </div>
  );
}
