"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useFamily } from "@/app/FamilyProvider";
import { Button } from "@/components/ui";

interface PackingItem {
  id: string;
  name: string;
  sizeLabel: string;
  thumbUrl: string;
  checked: boolean;
}

type PackingGroups = Record<string, PackingItem[]>;

const SEASON_OPTS = ["summer", "monsoon", "winter"] as const;
const OCCASION_OPTS = ["everyday", "daycare", "festive", "photoshoot"] as const;
const CATEGORY_EMOJI: Record<string, string> = {
  onesie: "👶", top: "👕", bottom: "👖", dress: "👗",
  outerwear: "🧥", sleepwear: "😴", accessory: "🎀",
};

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

  const [season, setSeason] = useState<string>("");
  const [occasion, setOccasion] = useState<string>("");
  const [groups, setGroups] = useState<PackingGroups | null>(null);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  const generate = async () => {
    if (!childId) return;
    setLoading(true);
    try {
      const params = new URLSearchParams({ childId });
      if (season) params.set("season", season);
      if (occasion) params.set("occasion", occasion);
      const res = await fetch(`/api/garments/packing?${params}`);
      const data = await res.json();
      setGroups(data.groups || {});
      setTotal(data.total || 0);
    } catch {}
    setLoading(false);
  };

  const toggleItem = (cat: string, itemId: string) => {
    if (!groups) return;
    setGroups(prev => ({
      ...prev!,
      [cat]: prev![cat].map(i => i.id === itemId ? { ...i, checked: !i.checked } : i),
    }));
  };

  const checkedCount = groups
    ? Object.values(groups).flat().filter(i => i.checked).length
    : 0;

  return (
    <div className="min-h-screen bg-gradient-to-br from-sky-50 via-purple-50 to-pink-50 dark:from-gray-900 dark:to-gray-800 pb-24">
      <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">🧳 Packing List</h1>
      </div>

      {/* Filters */}
      <div className="mx-4 bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm mb-4 space-y-4">
        <div>
          <p className="text-sm font-semibold text-gray-600 dark:text-gray-300 mb-2">Season</p>
          <div className="flex gap-2 flex-wrap">
            <button
              onClick={() => setSeason("")}
              className={`px-3 py-1.5 rounded-full text-sm font-medium ${!season ? "bg-rose-400 text-white" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"}`}
            >
              Any
            </button>
            {SEASON_OPTS.map(s => (
              <button
                key={s}
                onClick={() => setSeason(season === s ? "" : s)}
                className={`px-3 py-1.5 rounded-full text-sm font-medium ${season === s ? "bg-rose-400 text-white" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"}`}
              >
                {s}
              </button>
            ))}
          </div>
        </div>

        <div>
          <p className="text-sm font-semibold text-gray-600 dark:text-gray-300 mb-2">Occasion</p>
          <div className="flex gap-2 flex-wrap">
            <button
              onClick={() => setOccasion("")}
              className={`px-3 py-1.5 rounded-full text-sm font-medium ${!occasion ? "bg-rose-400 text-white" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"}`}
            >
              Any
            </button>
            {OCCASION_OPTS.map(o => (
              <button
                key={o}
                onClick={() => setOccasion(occasion === o ? "" : o)}
                className={`px-3 py-1.5 rounded-full text-sm font-medium ${occasion === o ? "bg-rose-400 text-white" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"}`}
              >
                {o}
              </button>
            ))}
          </div>
        </div>

        <Button fullWidth onClick={generate} loading={loading} size="lg">
          Generate List
        </Button>
      </div>

      {groups && (
        <>
          <div className="mx-4 mb-3 flex items-center justify-between">
            <p className="text-sm text-gray-500">{total} garments found · {checkedCount} packed</p>
            {total === 0 && (
              <p className="text-sm text-amber-600">No matching garments — try broader filters</p>
            )}
          </div>

          <div className="mx-4 space-y-3">
            {Object.entries(groups).map(([cat, items]) => (
              <div key={cat} className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm overflow-hidden">
                <div className="px-4 py-2.5 bg-gray-50 dark:bg-gray-700 border-b border-gray-100 dark:border-gray-600 flex items-center gap-2">
                  <span className="text-lg">{CATEGORY_EMOJI[cat] || "👗"}</span>
                  <span className="font-semibold text-sm capitalize">{cat}</span>
                  <span className="ml-auto text-xs text-gray-400">{items.length}</span>
                </div>
                {items.map(item => (
                  <button
                    key={item.id}
                    onClick={() => toggleItem(cat, item.id)}
                    className="w-full flex items-center gap-3 px-4 py-3 border-b border-gray-50 dark:border-gray-700 last:border-0 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                  >
                    <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition-all ${
                      item.checked ? "border-rose-400 bg-rose-400" : "border-gray-300 dark:border-gray-500"
                    }`}>
                      {item.checked && <span className="text-white text-xs">✓</span>}
                    </div>
                    <div className="w-10 h-10 rounded-xl overflow-hidden flex-shrink-0">
                      <img src={item.thumbUrl} alt={item.name} className="w-full h-full object-cover" loading="lazy" />
                    </div>
                    <div className="flex-1 text-left">
                      <p className={`text-sm font-medium ${item.checked ? "line-through text-gray-400" : "text-gray-700 dark:text-gray-200"}`}>
                        {item.name}
                      </p>
                      <p className="text-xs text-gray-400">{item.sizeLabel}</p>
                    </div>
                  </button>
                ))}
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
