"use client";

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

interface OutfitItem {
  id: string;
  name: string | null;
  category: string;
  sizeLabel: string;
  thumbUrl: string;
  imageUrl: string;
  colors: string[];
}

interface OutfitSuggestion {
  label: string;
  items: OutfitItem[];
}

interface OutfitResponse {
  weatherBasis: string;
  weather: { tempC: number; season: string };
  outfits: OutfitSuggestion[];
}

const OCCASION_OPTS = ["", "everyday", "daycare", "festive", "photoshoot"] as const;
const SEASON_ICON: Record<string, string> = {
  summer: "☀️", monsoon: "🌧️", winter: "❄️",
};

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

  const [occasion, setOccasion] = useState("");
  const [result, setResult] = useState<OutfitResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [savedOutfitName, setSavedOutfitName] = useState<Record<number, string>>({});
  const [savedIdx, setSavedIdx] = useState<Set<number>>(new Set());

  const fetchSuggestions = async () => {
    if (!childId) return;
    setLoading(true);
    try {
      const params = new URLSearchParams({ childId });
      if (occasion) params.set("occasion", occasion);
      const res = await fetch(`/api/garments/outfit?${params}`);
      const data = await res.json();
      setResult(data);
    } catch {}
    setLoading(false);
  };

  useEffect(() => { fetchSuggestions(); }, [childId]);

  const saveOutfit = async (idx: number, outfit: OutfitSuggestion) => {
    const name = savedOutfitName[idx]?.trim() || outfit.label;
    if (!childId) return;
    try {
      const res = await fetch("/api/garments/outfits", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          childId,
          name,
          garmentIds: outfit.items.map(i => i.id),
          occasionTags: occasion ? [occasion] : [],
        }),
      });
      if (res.ok) setSavedIdx(prev => new Set([...prev, idx]));
    } catch {}
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-yellow-50 via-orange-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">✨ Today&apos;s Outfit</h1>
        <button
          onClick={fetchSuggestions}
          className="ml-auto p-2 rounded-xl bg-white dark:bg-gray-800 shadow-sm text-lg"
          title="Refresh"
        >
          🔄
        </button>
      </div>

      {/* Weather basis */}
      {result && (
        <div className="mx-4 mb-4 p-3 bg-white dark:bg-gray-800 rounded-2xl shadow-sm flex items-center gap-3">
          <span className="text-2xl">{SEASON_ICON[result.weather.season] || "🌤️"}</span>
          <div>
            <p className="text-sm font-semibold text-gray-700 dark:text-gray-200">{result.weatherBasis}</p>
            <p className="text-xs text-gray-400">Suggestions filtered for {result.weather.season} garments</p>
          </div>
        </div>
      )}

      {/* Occasion filter */}
      <div className="px-4 mb-4 flex gap-2 overflow-x-auto scrollbar-hide">
        {OCCASION_OPTS.map(o => (
          <button
            key={o || "all"}
            onClick={() => { setOccasion(o); }}
            className={`px-3 py-1.5 rounded-full text-sm font-medium whitespace-nowrap flex-shrink-0 transition-all ${
              occasion === o ? "bg-rose-400 text-white" : "bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300"
            }`}
          >
            {o || "Any occasion"}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="flex flex-col items-center justify-center py-16 gap-3">
          <div className="flex gap-1">
            {[0, 150, 300].map(d => (
              <span key={d} className="w-2.5 h-2.5 bg-rose-400 rounded-full animate-bounce" style={{ animationDelay: `${d}ms` }} />
            ))}
          </div>
          <p className="text-sm text-gray-500">Fetching weather + building outfits…</p>
        </div>
      ) : result && result.outfits.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 px-8 text-center">
          <span className="text-5xl mb-4">🌂</span>
          <p className="font-semibold text-gray-600 dark:text-gray-300">No outfits for today&apos;s weather</p>
          <p className="text-sm text-gray-400 mt-1">
            Add more {result.weather.season} garments to your wardrobe
          </p>
          <button
            onClick={() => router.push("/wardrobe/add")}
            className="mt-4 px-5 py-2 bg-rose-400 text-white rounded-xl text-sm font-medium"
          >
            + Add Garment
          </button>
        </div>
      ) : result ? (
        <div className="mx-4 space-y-4">
          {result.outfits.map((outfit, idx) => (
            <div key={idx} className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm overflow-hidden">
              <div className="px-4 pt-3 pb-2 flex items-center justify-between">
                <span className="text-sm font-semibold text-gray-700 dark:text-gray-200">
                  Outfit {idx + 1} — {outfit.label}
                </span>
                {outfit.items[0]?.colors?.length > 0 && (
                  <span className="text-xs text-gray-400">{outfit.items.flatMap(i => i.colors).slice(0, 3).join(", ")}</span>
                )}
              </div>

              <div className={`flex gap-3 px-4 pb-3 ${outfit.items.length === 1 ? "justify-center" : ""}`}>
                {outfit.items.map(item => (
                  <div key={item.id} className="flex flex-col items-center gap-1.5">
                    <div className="w-28 h-28 rounded-xl overflow-hidden bg-gray-50">
                      <img src={item.thumbUrl} alt={item.name || item.category} className="w-full h-full object-cover" />
                    </div>
                    <p className="text-xs text-center text-gray-600 dark:text-gray-400 max-w-24 truncate">
                      {item.name || item.category}
                    </p>
                    <span className="text-xs bg-gray-100 dark:bg-gray-700 text-gray-500 px-1.5 py-0.5 rounded-full">
                      {item.sizeLabel}
                    </span>
                  </div>
                ))}
              </div>

              {/* Save outfit */}
              {savedIdx.has(idx) ? (
                <div className="px-4 pb-3 text-sm text-green-600 dark:text-green-400">✓ Saved to wardrobe</div>
              ) : (
                <div className="px-4 pb-3 flex gap-2">
                  <input
                    value={savedOutfitName[idx] ?? ""}
                    onChange={e => setSavedOutfitName(prev => ({ ...prev, [idx]: e.target.value }))}
                    placeholder={outfit.label}
                    className="flex-1 px-3 py-1.5 rounded-xl bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 text-sm focus:outline-none"
                  />
                  <button
                    onClick={() => saveOutfit(idx, outfit)}
                    className="px-3 py-1.5 bg-indigo-400 text-white rounded-xl text-sm font-medium"
                  >
                    💾 Save
                  </button>
                </div>
              )}
            </div>
          ))}

          <Button fullWidth variant="secondary" onClick={fetchSuggestions} size="lg">
            🔄 Suggest again
          </Button>
        </div>
      ) : null}
    </div>
  );
}
