"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useFamily } from "@/app/FamilyProvider";
import { GARMENT_CATEGORIES, GARMENT_SIZE_ORDER } from "@/db/schema/wardrobe";

interface Garment {
  id: string;
  name: string | null;
  category: string;
  sizeLabel: string;
  thumbUrl: string;
  status: string;
  seasons: string[];
  occasionTags: string[];
  colors: string[];
}

interface OutgrowthNudge {
  candidates: { id: string; sizeLabel: string }[];
  currentSizeLabel: string | null;
}

const STATUS_OPTS = [
  { value: "active", label: "Active" },
  { value: "stored", label: "Stored" },
  { value: "outgrown", label: "Outgrown" },
  { value: "donated", label: "Donated" },
];

const CATEGORY_EMOJI: Record<string, string> = {
  onesie: "👶", top: "👕", bottom: "👖", dress: "👗",
  outerwear: "🧥", sleepwear: "😴", accessory: "🎀",
};

export default function WardrobePage() {
  const { childId } = useFamily();
  const router = useRouter();

  const [garments, setGarments] = useState<Garment[]>([]);
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState("active");
  const [filterCategory, setFilterCategory] = useState("");
  const [filterSize, setFilterSize] = useState("");
  const [filterSeason, setFilterSeason] = useState("");
  const [nudge, setNudge] = useState<OutgrowthNudge | null>(null);
  const [nudgeDismissed, setNudgeDismissed] = useState(false);

  const fetchGarments = useCallback(async () => {
    if (!childId) return;
    setLoading(true);
    try {
      const params = new URLSearchParams({ childId, status });
      if (filterCategory) params.set("category", filterCategory);
      if (filterSize) params.set("sizeLabel", filterSize);
      if (filterSeason) params.set("season", filterSeason);
      const res = await fetch(`/api/garments?${params}`);
      const data = await res.json();
      setGarments(data.items || []);
    } catch {
      setGarments([]);
    } finally {
      setLoading(false);
    }
  }, [childId, status, filterCategory, filterSize, filterSeason]);

  const fetchNudge = useCallback(async () => {
    if (!childId || nudgeDismissed) return;
    try {
      const res = await fetch(`/api/garments/outgrowth?childId=${childId}`);
      const data = await res.json();
      if (data.candidates?.length > 0) setNudge(data);
    } catch {}
  }, [childId, nudgeDismissed]);

  useEffect(() => { fetchGarments(); }, [fetchGarments]);
  useEffect(() => { fetchNudge(); }, [fetchNudge]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-50 via-purple-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 pb-24">
      {/* Header */}
      <div className="flex items-center gap-3 p-4">
        <button onClick={() => router.back()} className="p-2 rounded-xl bg-white dark:bg-gray-800 shadow-sm text-xl">←</button>
        <h1 className="text-xl font-bold">Wardrobe 👗</h1>
        <div className="ml-auto flex gap-2">
          <Link href="/wardrobe/outfit" className="p-2 rounded-xl bg-white dark:bg-gray-800 shadow-sm text-lg" title="Today's outfit">✨</Link>
          <Link href="/wardrobe/packing" className="p-2 rounded-xl bg-white dark:bg-gray-800 shadow-sm text-lg" title="Packing list">🧳</Link>
          <Link href="/wardrobe/saved-outfits" className="p-2 rounded-xl bg-white dark:bg-gray-800 shadow-sm text-lg" title="Saved outfits">💾</Link>
          <Link href="/wardrobe/add" className="px-3 py-2 rounded-xl bg-rose-400 text-white text-sm font-medium shadow-sm">+ Add</Link>
        </div>
      </div>

      {/* Outgrowth nudge */}
      {nudge && !nudgeDismissed && (
        <div className="mx-4 mb-3 p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700 rounded-2xl flex items-start gap-3">
          <span className="text-2xl mt-0.5">📦</span>
          <div className="flex-1">
            <p className="text-sm font-semibold text-amber-800 dark:text-amber-200">
              {nudge.candidates.length} item{nudge.candidates.length !== 1 ? "s" : ""} not worn in 45+ days and may be outgrown
            </p>
            <p className="text-xs text-amber-600 dark:text-amber-400 mt-0.5">
              Current size: <strong>{nudge.currentSizeLabel}</strong>
            </p>
            <div className="flex gap-2 mt-2">
              <button
                onClick={() => { setFilterSize(nudge.candidates[0].sizeLabel); setNudgeDismissed(true); }}
                className="text-xs px-2 py-1 bg-amber-400 text-white rounded-lg"
              >
                View items
              </button>
              <button onClick={() => setNudgeDismissed(true)} className="text-xs px-2 py-1 text-amber-600 dark:text-amber-400">
                Dismiss
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="px-4 space-y-2 mb-4">
        {/* Status row */}
        <div className="flex gap-2 overflow-x-auto scrollbar-hide pb-1">
          {STATUS_OPTS.map(s => (
            <button
              key={s.value}
              onClick={() => setStatus(s.value)}
              className={`px-3 py-1.5 rounded-full text-sm font-medium whitespace-nowrap flex-shrink-0 transition-all ${
                status === s.value
                  ? "bg-rose-400 text-white"
                  : "bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300"
              }`}
            >
              {s.label}
            </button>
          ))}
        </div>

        {/* Category row */}
        <div className="flex gap-2 overflow-x-auto scrollbar-hide pb-1">
          <button
            onClick={() => setFilterCategory("")}
            className={`px-3 py-1 rounded-full text-sm whitespace-nowrap flex-shrink-0 transition-all ${
              !filterCategory ? "bg-indigo-400 text-white" : "bg-white dark:bg-gray-800 text-gray-500"
            }`}
          >
            All
          </button>
          {GARMENT_CATEGORIES.map(c => (
            <button
              key={c}
              onClick={() => setFilterCategory(filterCategory === c ? "" : c)}
              className={`px-3 py-1 rounded-full text-sm whitespace-nowrap flex-shrink-0 transition-all ${
                filterCategory === c ? "bg-indigo-400 text-white" : "bg-white dark:bg-gray-800 text-gray-500"
              }`}
            >
              {CATEGORY_EMOJI[c]} {c}
            </button>
          ))}
        </div>

        {/* Size row */}
        <div className="flex gap-2 overflow-x-auto scrollbar-hide pb-1">
          <button
            onClick={() => setFilterSize("")}
            className={`px-3 py-1 rounded-full text-xs whitespace-nowrap flex-shrink-0 transition-all ${
              !filterSize ? "bg-teal-400 text-white" : "bg-white dark:bg-gray-800 text-gray-500"
            }`}
          >
            Any size
          </button>
          {GARMENT_SIZE_ORDER.map(s => (
            <button
              key={s}
              onClick={() => setFilterSize(filterSize === s ? "" : s)}
              className={`px-3 py-1 rounded-full text-xs whitespace-nowrap flex-shrink-0 transition-all ${
                filterSize === s ? "bg-teal-400 text-white" : "bg-white dark:bg-gray-800 text-gray-500"
              }`}
            >
              {s}
            </button>
          ))}
        </div>

        {/* Season row */}
        <div className="flex gap-2 pb-1">
          {["", "summer", "monsoon", "winter"].map(s => (
            <button
              key={s || "all"}
              onClick={() => setFilterSeason(s)}
              className={`px-3 py-1 rounded-full text-xs whitespace-nowrap transition-all ${
                filterSeason === s ? "bg-orange-400 text-white" : "bg-white dark:bg-gray-800 text-gray-500"
              }`}
            >
              {s || "All seasons"}
            </button>
          ))}
        </div>
      </div>

      {/* Grid */}
      {loading ? (
        <div className="grid grid-cols-3 gap-3 px-4">
          {[...Array(9)].map((_, i) => (
            <div key={i} className="aspect-square rounded-2xl bg-white dark:bg-gray-800 animate-pulse" />
          ))}
        </div>
      ) : garments.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 px-8 text-center">
          <span className="text-5xl mb-4">👚</span>
          <p className="font-semibold text-gray-600 dark:text-gray-300">No garments yet</p>
          <p className="text-sm text-gray-400 mt-1">Add your first garment to build the wardrobe catalogue</p>
          <Link href="/wardrobe/add" className="mt-4 px-5 py-2 bg-rose-400 text-white rounded-xl text-sm font-medium">
            + Add Garment
          </Link>
        </div>
      ) : (
        <div className="grid grid-cols-3 gap-3 px-4">
          {garments.map(g => (
            <Link
              key={g.id}
              href={`/wardrobe/${g.id}`}
              className="flex flex-col bg-white dark:bg-gray-800 rounded-2xl overflow-hidden shadow-sm hover:shadow-md transition-shadow"
            >
              <div className="aspect-square relative">
                <img
                  src={g.thumbUrl}
                  alt={g.name || g.category}
                  className="w-full h-full object-cover"
                  loading="lazy"
                />
                <span className="absolute top-1 right-1 text-xs bg-white/90 dark:bg-gray-900/90 px-1.5 py-0.5 rounded-full font-medium text-gray-700 dark:text-gray-200">
                  {g.sizeLabel}
                </span>
              </div>
              <div className="px-2 py-1.5">
                <p className="text-xs font-medium text-gray-700 dark:text-gray-200 truncate">
                  {g.name || `${CATEGORY_EMOJI[g.category] || ""} ${g.category}`}
                </p>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
