"use client";

import React, { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { 
  FolderKanban, 
  CheckCircle2, 
  ArrowRight,
  TrendingUp,
  X,
  ExternalLink,
  Maximize2
} from "lucide-react";
import { SectionCorners } from "@/components/ui/SectionCorner";
import { ShinyButton } from "@/components/ui/ShinyButton";
import { BlinkingSquares } from "@/components/ui/BlinkingSquares";
import { useAppStore, INITIAL_PORTFOLIO } from "@/lib/store";
import { PortfolioItem } from "@/types";

export default function PortfolioPage() {
  const store = useAppStore();
  const { t } = store;
  const portfolio = (store.portfolio && store.portfolio.length > 0) ? store.portfolio : INITIAL_PORTFOLIO;
  const [selectedCategory, setSelectedCategory] = useState<string>("All");
  const [activeCaseStudy, setActiveCaseStudy] = useState<PortfolioItem | null>(null);

  const categories = ["All", "Web App", "E-Commerce", "NGO & Social", "SaaS"];

  const filteredPortfolio =
    selectedCategory === "All"
      ? portfolio
      : portfolio.filter((p) => p.category === selectedCategory);

  return (
    <div className="mx-auto flex min-h-screen w-[calc(100%-1.5rem)] max-w-[1440px] flex-col border-x border-border sm:w-[calc(100%-2.5rem)] lg:w-[calc(100%-3rem)] bg-background">
      {/* Header Banner */}
      <section className="relative border-b border-border p-6 sm:p-10 lg:p-14 overflow-hidden">
        <SectionCorners />
        <BlinkingSquares
          squareSize={20}
          gap={8}
          color="#024d37"
          maxOpacity={0.35}
          minOpacity={0.03}
          blinkProbability={0.02}
          className="opacity-50"
        />

        <div className="relative z-10 max-w-3xl">
          <div className="inline-flex items-center gap-2 rounded-full border border-border bg-muted px-3.5 py-1 text-xs font-mono font-medium text-foreground mb-6">
            <span className="h-2 w-2 rounded-full bg-[#024d37] animate-pulse" />
            // {t("portfolio.badge")}
          </div>
          <h1 className="text-4xl font-semibold leading-[1.05] tracking-tight text-foreground sm:text-5xl lg:text-[3.8rem]">
            {t("portfolio.title")}
          </h1>
          <p className="mt-4 text-sm text-muted-foreground leading-relaxed sm:text-base">
            {t("portfolio.desc")}
          </p>
        </div>
      </section>

      {/* Filter Tabs */}
      <section className="relative border-b border-border p-6 sm:p-10 lg:p-14">
        <SectionCorners />

        <div className="flex gap-2 mb-10 overflow-x-auto pb-2 font-mono text-xs">
          {categories.map((cat) => (
            <button
              key={cat}
              onClick={() => setSelectedCategory(cat)}
              className={`rounded-full px-5 py-2 uppercase tracking-wider transition-colors ${
                selectedCategory === cat
                  ? "bg-[#024d37] text-white font-bold shadow-sm"
                  : "border border-border bg-card text-muted-foreground hover:text-foreground"
              }`}
            >
              {cat}
            </button>
          ))}
        </div>

        {/* Portfolio Cards Grid with High-Res Screenshots */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
          {filteredPortfolio.map((item, idx) => (
            <article
              key={item.id}
              className="flex flex-col justify-between rounded-3xl border border-border bg-card overflow-hidden hover:border-[#024d37]/50 transition-all shadow-sm group"
            >
              {/* Screenshot Preview Image */}
              <div 
                onClick={() => setActiveCaseStudy(item)}
                className="relative h-52 sm:h-60 w-full overflow-hidden bg-muted cursor-pointer border-b border-border"
              >
                <Image
                  src={item.image || "/assets/services/2.png"}
                  alt={`${item.name} Interface Screenshot`}
                  fill
                  className="object-cover object-top group-hover:scale-105 transition-transform duration-500"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-end p-4">
                  <span className="inline-flex items-center gap-1.5 rounded-full bg-white/20 backdrop-blur-md px-3 py-1 text-xs text-white font-mono font-semibold">
                    <Maximize2 className="h-3 w-3" /> View Architecture Breakdown
                  </span>
                </div>
              </div>

              {/* Body Content */}
              <div className="p-6 sm:p-7 space-y-4 flex-1 flex flex-col justify-between">
                <div className="space-y-3">
                  <div className="flex items-center justify-between font-mono text-xs">
                    <span className="text-[#024d37] font-semibold">
                      // CASE_0{idx + 1}
                    </span>
                    <span className="rounded-full border border-border bg-muted px-2.5 py-0.5 text-[10px] text-foreground uppercase">
                      {item.category}
                    </span>
                  </div>

                  <h3 className="text-xl sm:text-2xl font-bold tracking-tight text-foreground group-hover:text-[#024d37] transition-colors">
                    {item.name}
                  </h3>
                  <p className="text-xs font-mono text-muted-foreground">Client: {item.client}</p>

                  <p className="text-xs text-muted-foreground leading-relaxed line-clamp-3">
                    {item.description}
                  </p>

                  <div className="space-y-1.5 pt-3 border-t border-border font-mono text-xs">
                    {item.results.map((res, i) => (
                      <div key={i} className="flex items-start gap-2 text-[11px] text-foreground/90">
                        <span className="text-[#024d37] font-bold">✓</span>
                        <span className="truncate">{res}</span>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="pt-4 border-t border-border flex items-center justify-between font-mono text-xs text-muted-foreground">
                  <span className="text-[11px] truncate max-w-[160px]">{item.tech_stack.slice(0, 2).join(" • ")}</span>
                  <button
                    onClick={() => setActiveCaseStudy(item)}
                    className="text-[#024d37] font-semibold hover:underline flex items-center gap-1"
                  >
                    Deep Study →
                  </button>
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>

      {/* Case Study Modal with Full Screenshot */}
      {activeCaseStudy && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-background/80 backdrop-blur-sm" onClick={() => setActiveCaseStudy(null)} />
          <div className="relative z-10 w-full max-w-3xl rounded-3xl border border-border bg-card p-6 sm:p-8 text-foreground shadow-2xl space-y-6 max-h-[90vh] overflow-y-auto font-mono text-xs">
            <div className="flex items-center justify-between border-b border-border pb-4">
              <div>
                <span className="text-[#024d37] font-semibold">// CASE STUDY ARCHITECTURE BREAKDOWN</span>
                <h3 className="text-2xl font-bold font-sans mt-1 text-foreground">{activeCaseStudy.name}</h3>
                <p className="text-xs text-muted-foreground">Client: {activeCaseStudy.client} • Category: {activeCaseStudy.category}</p>
              </div>
              <button
                onClick={() => setActiveCaseStudy(null)}
                className="rounded-full p-2 text-muted-foreground hover:text-foreground"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* High-Res Image in Modal */}
            <div className="relative h-64 sm:h-80 w-full overflow-hidden rounded-2xl border border-border bg-muted shadow-md">
              <Image
                src={activeCaseStudy.image || "/assets/services/2.png"}
                alt={activeCaseStudy.name}
                fill
                className="object-cover object-top"
              />
            </div>

            <p className="text-xs sm:text-sm font-sans text-muted-foreground leading-relaxed">
              {activeCaseStudy.description}
            </p>

            <div>
              <h4 className="uppercase tracking-wider text-foreground font-bold mb-3">// VERIFIED DELIVERABLES & METRICS:</h4>
              <ul className="space-y-2 text-xs font-sans text-foreground">
                {activeCaseStudy.results.map((r, i) => (
                  <li key={i} className="flex items-center gap-2">
                    <span className="font-mono text-[#024d37] font-bold">✓</span>
                    <span>{r}</span>
                  </li>
                ))}
              </ul>
            </div>

            <div>
              <h4 className="uppercase tracking-wider text-foreground font-bold mb-2">// PRODUCTION TECH STACK:</h4>
              <div className="flex flex-wrap gap-2">
                {activeCaseStudy.tech_stack.map((tech, i) => (
                  <span key={i} className="rounded-lg border border-border bg-muted px-2.5 py-1 text-xs text-foreground">
                    {tech}
                  </span>
                ))}
              </div>
            </div>

            <div className="flex justify-end gap-3 pt-4 border-t border-border">
              <button
                onClick={() => setActiveCaseStudy(null)}
                className="rounded-full border border-border px-5 py-2 text-xs text-muted-foreground hover:text-foreground"
              >
                Close
              </button>
              <ShinyButton href="/contact" className="text-xs">
                Build Similar Architecture →
              </ShinyButton>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
