"use client";

import { useState } from "react";
import Image from "next/image";
import {
  Scan,
  Waves,
  Shield,
  Bot,
  Radio,
  Radar,
  Paintbrush,
  Anchor,
  Loader2,
} from "lucide-react";
import type { LucideProps } from "lucide-react";
import FadeIn from "@/components/animations/FadeIn";
import TechVideoPlayer from "@/components/TechVideoPlayer";
import { Button } from "@/components/ui/button";
import { getTechPageTechnologies } from "@/services/pages/public/technologies/client";
import type { TechPageTechnology, TechPageMeta } from "@/services/pages/public/technologies";

type IconComponent = React.ComponentType<LucideProps>;

const SLUG_ICON_MAP: Record<string, IconComponent> = {
  "slofec-floorscanner": Scan,
  "acfm-eddy-current": Waves,
  "cui-pulsed-eddy-current-lyft": Shield,
  "magg310-underwater-robot": Bot,
  "focus-guided-wave-testing": Radio,
  "sludge-profiling-of-oil-tanks": Radar,
  "robotic-blasting-surface-prep": Paintbrush,
  "coffer-dams": Anchor,
};

function resolveIcon(slug: string): IconComponent {
  return SLUG_ICON_MAP[slug] ?? Scan;
}

interface Props {
  initialData: TechPageTechnology[];
  initialMeta: TechPageMeta;
}

function TechCard({ tech, index }: { tech: TechPageTechnology; index: number }) {
  const Icon = resolveIcon(tech.slug);
  const isEven = index % 2 === 0;

  return (
    <FadeIn
      as="section"
      id={tech.slug}
      y={40}
      margin="-100px"
      duration={0.6}
      className="petro-section border-b border-border last:border-b-0"
    >
      <div className="petro-container">
        <div className={`grid lg:grid-cols-2 gap-12 items-start ${!isEven ? "lg:direction-rtl" : ""}`}>
          {/* Image / Video */}
          <div className={`${!isEven ? "lg:order-2" : ""}`}>
            <FadeIn>
              <TechVideoPlayer
                img={tech.image_path ?? ""}
                alt={tech.name}
                name={tech.name}
                subtitle={tech.subtitle ?? ""}
                iconNode={<Icon className="w-5 h-5 text-accent-foreground" />}
                video={tech.video_path ?? undefined}
              />
            </FadeIn>
          </div>

          {/* Content */}
          <div className={`space-y-8 ${!isEven ? "lg:order-1" : ""}`}>
            <div>
              <h2 className="text-2xl md:text-3xl font-bold text-foreground mb-4">{tech.name}</h2>
              {tech.overview && (
                <p className="text-muted-foreground leading-relaxed">{tech.overview}</p>
              )}
            </div>

            {tech.how_it_works && (
              <div>
                <h4 className="text-sm font-bold uppercase tracking-[0.2em] text-primary mb-3">
                  How It Works
                </h4>
                <p className="text-muted-foreground text-sm leading-relaxed">{tech.how_it_works}</p>
              </div>
            )}

            {/* Specs */}
            {(tech.specs ?? []).length > 0 && (
              <div>
                <h4 className="text-sm font-bold uppercase tracking-[0.2em] text-primary mb-3">
                  Technical Specifications
                </h4>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {(tech.specs ?? []).map((spec, i) => (
                    <div key={i} className="bg-secondary rounded-sm p-3">
                      <p className="text-xs text-muted-foreground uppercase tracking-wider">{spec.label}</p>
                      <p className="text-sm font-semibold text-foreground mt-1">{spec.value}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Applications */}
            {(tech.applications ?? []).length > 0 && (
              <div>
                <h4 className="text-sm font-bold uppercase tracking-[0.2em] text-primary mb-3">
                  Key Applications
                </h4>
                <ul className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  {(tech.applications ?? []).map((app, i) => (
                    <li key={i} className="flex items-start gap-2 text-sm text-muted-foreground">
                      <div className="w-1.5 h-1.5 rounded-full bg-accent mt-1.5 shrink-0" />
                      {app}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </div>
      </div>
    </FadeIn>
  );
}

export function TechnologiesGrid({ initialData, initialMeta }: Props) {
  const [data, setData] = useState(initialData);
  const [meta, setMeta] = useState(initialMeta);
  const [loading, setLoading] = useState(false);

  const loadMore = async () => {
    if (!meta.has_more || !meta.next_cursor || loading) return;
    setLoading(true);
    try {
      const { data: next, meta: nextMeta } = await getTechPageTechnologies(meta.next_cursor);
      setData((prev) => [...prev, ...next]);
      setMeta(nextMeta);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* Sticky Quick Nav */}
      <div className="sticky top-20 z-40 bg-card shadow-sm border-b border-border">
        <div className="petro-container">
          <div className="flex overflow-x-auto gap-1 py-2 scrollbar-hide">
            {data.map((tech) => {
              const Icon = resolveIcon(tech.slug);
              return (
                <a
                  key={tech.slug}
                  href={`#${tech.slug}`}
                  className="flex items-center gap-2 px-4 py-2 text-xs font-medium text-muted-foreground hover:text-accent whitespace-nowrap transition-colors rounded-sm hover:bg-secondary"
                >
                  <Icon className="w-3.5 h-3.5" />
                  {tech.name.split(" ")[0]}
                </a>
              );
            })}
          </div>
        </div>
      </div>

      {/* Overview Grid */}
      <section className="petro-section">
        <div className="petro-container">
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {data.map((tech, i) => {
              const Icon = resolveIcon(tech.slug);
              return (
                <FadeIn
                  as="a"
                  key={tech.slug}
                  href={`#${tech.slug}`}
                  y={20}
                  delay={i * 0.05}
                  duration={0.4}
                  className="petro-card p-5 group cursor-pointer hover:-translate-y-1 transition-all duration-300"
                >
                  <div className="w-10 h-10 rounded-sm bg-primary/10 flex items-center justify-center mb-4 group-hover:bg-accent transition-colors">
                    <Icon className="w-5 h-5 text-primary group-hover:text-accent-foreground transition-colors" />
                  </div>
                  <h3 className="font-bold text-foreground text-sm mb-1">{tech.name}</h3>
                  <p className="text-xs text-muted-foreground">{tech.subtitle}</p>
                </FadeIn>
              );
            })}
          </div>
        </div>
      </section>

      {/* Detail Sections */}
      {data.map((tech, i) => (
        <TechCard key={tech.slug} tech={tech} index={i} />
      ))}

      {/* Load More */}
      {meta.has_more && (
        <div className="py-12 flex justify-center">
          <Button
            variant="outline"
            onClick={loadMore}
            disabled={loading}
            className="min-w-[180px]"
          >
            {loading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Loading…
              </>
            ) : (
              "Load More Technologies"
            )}
          </Button>
        </div>
      )}
    </>
  );
}
