"use client";

import { useState, useEffect } from "react";
import { useRouter, useParams } from "next/navigation";
import { Button } from "@/components/ui";
import { GARMENT_CATEGORIES, GARMENT_SIZE_ORDER } from "@/db/schema/wardrobe";

interface Garment {
  id: string;
  name: string | null;
  category: string;
  sizeLabel: string;
  colors: string[];
  seasons: string[];
  occasionTags: string[];
  imageKey: string;
  thumbKey: string;
  imageUrl: string;
  thumbUrl: string;
  status: string;
  acquiredVia: string | null;
  giftFrom: string | null;
  visionMetadata: unknown;
  createdAt: string;
  updatedAt: string;
}

interface Wear {
  id: string;
  worn_on: string;
  memory_id: string | null;
}

const STATUS_FLOW = ["active", "stored", "outgrown", "donated"] as const;
const STATUS_COLORS: Record<string, string> = {
  active: "bg-green-100 text-green-700",
  stored: "bg-blue-100 text-blue-700",
  outgrown: "bg-amber-100 text-amber-700",
  donated: "bg-gray-100 text-gray-600",
};
const CATEGORY_LABELS: Record<string, string> = {
  onesie: "Onesie", top: "Top", bottom: "Bottom", dress: "Dress",
  outerwear: "Jacket", sleepwear: "Sleepwear", accessory: "Accessory",
};

function Chip({ label, color }: { label: string; color?: string }) {
  return (
    <span className={`px-2.5 py-1 rounded-full text-xs font-medium ${color || "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"}`}>
      {label}
    </span>
  );
}

export default function GarmentDetailPage() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;

  const [garment, setGarment] = useState<Garment | null>(null);
  const [wears, setWears] = useState<Wear[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [loggingWear, setLoggingWear] = useState(false);
  const [error, setError] = useState("");

  // Edit state
  const [editName, setEditName] = useState("");
  const [editCategory, setEditCategory] = useState("");
  const [editSize, setEditSize] = useState("");
  const [editStatus, setEditStatus] = useState("");
  const [editColors, setEditColors] = useState<string[]>([]);
  const [editSeasons, setEditSeasons] = useState<string[]>([]);
  const [editOccasions, setEditOccasions] = useState<string[]>([]);
  const [editColorInput, setEditColorInput] = useState("");
  const [editAcquiredVia, setEditAcquiredVia] = useState<string | null>(null);
  const [editGiftFrom, setEditGiftFrom] = useState("");

  const load = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/garments/${id}`);
      if (!res.ok) { router.replace("/wardrobe"); return; }
      const data = await res.json();
      setGarment(data.item);
      setWears(data.wears || []);
    } catch {
      router.replace("/wardrobe");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); }, [id]);

  const startEdit = () => {
    if (!garment) return;
    setEditName(garment.name || "");
    setEditCategory(garment.category);
    setEditSize(garment.sizeLabel);
    setEditStatus(garment.status);
    setEditColors([...garment.colors]);
    setEditSeasons([...garment.seasons]);
    setEditOccasions([...garment.occasionTags]);
    setEditAcquiredVia(garment.acquiredVia);
    setEditGiftFrom(garment.giftFrom || "");
    setEditing(true);
  };

  const saveEdit = async () => {
    setSaving(true);
    setError("");
    try {
      const res = await fetch(`/api/garments/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: editName || null,
          category: editCategory,
          sizeLabel: editSize,
          status: editStatus,
          colors: editColors,
          seasons: editSeasons,
          occasionTags: editOccasions,
          acquiredVia: editAcquiredVia,
          giftFrom: editGiftFrom || null,
        }),
      });
      if (!res.ok) throw new Error((await res.json()).error);
      const data = await res.json();
      setGarment(data.item);
      setEditing(false);
    } catch (err) {
      setError(`Save failed: ${err}`);
    } finally {
      setSaving(false);
    }
  };

  const logWear = async () => {
    setLoggingWear(true);
    try {
      const res = await fetch(`/api/garments/${id}/wear`, { method: "POST" });
      if (res.ok) {
        const data = await res.json();
        setWears(prev => [data.wear, ...prev]);
      }
    } catch {}
    setLoggingWear(false);
  };

  const updateStatus = async (newStatus: string) => {
    try {
      const res = await fetch(`/api/garments/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: newStatus }),
      });
      if (res.ok) {
        const data = await res.json();
        setGarment(data.item);
      }
    } catch {}
  };

  const toggleArray = (arr: string[], val: string) =>
    arr.includes(val) ? arr.filter(x => x !== val) : [...arr, val];

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-pink-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 flex items-center justify-center">
        <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>
      </div>
    );
  }

  if (!garment) return null;

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-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-lg font-bold truncate">{garment.name || CATEGORY_LABELS[garment.category] || garment.category}</h1>
        <button
          onClick={editing ? () => setEditing(false) : startEdit}
          className="ml-auto text-sm px-3 py-1.5 bg-white dark:bg-gray-800 rounded-xl shadow-sm"
        >
          {editing ? "Cancel" : "Edit"}
        </button>
      </div>

      {error && (
        <div className="mx-4 mb-3 p-3 bg-red-50 rounded-xl text-sm text-red-700">{error}</div>
      )}

      {!editing ? (
        /* ─── View mode ─── */
        <div className="mx-4 space-y-3">
          {/* Full-res image */}
          <div className="rounded-3xl overflow-hidden shadow-lg">
            <img src={garment.imageUrl} alt={garment.name || garment.category} className="w-full object-contain max-h-80 bg-white dark:bg-gray-800" />
          </div>

          {/* Status + quick actions */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <div className="flex items-center justify-between mb-3">
              <span className={`px-3 py-1 rounded-full text-sm font-semibold ${STATUS_COLORS[garment.status] || "bg-gray-100"}`}>
                {garment.status}
              </span>
              <Button size="sm" loading={loggingWear} onClick={logWear} variant="secondary">
                👕 Worn today
              </Button>
            </div>
            <div className="flex gap-2 flex-wrap">
              {STATUS_FLOW.filter(s => s !== garment.status).map(s => (
                <button
                  key={s}
                  onClick={() => updateStatus(s)}
                  className="text-xs px-2.5 py-1 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded-full hover:bg-gray-200 dark:hover:bg-gray-600"
                >
                  Move to {s}
                </button>
              ))}
            </div>
          </div>

          {/* Details */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <p className="text-xs text-gray-400">Category</p>
                <p className="font-medium text-sm">{CATEGORY_LABELS[garment.category] || garment.category}</p>
              </div>
              <div>
                <p className="text-xs text-gray-400">Size</p>
                <p className="font-medium text-sm">{garment.sizeLabel}</p>
              </div>
              {garment.acquiredVia && (
                <div>
                  <p className="text-xs text-gray-400">Acquired via</p>
                  <p className="font-medium text-sm">{garment.acquiredVia}</p>
                </div>
              )}
              {garment.giftFrom && (
                <div>
                  <p className="text-xs text-gray-400">Gift from</p>
                  <p className="font-medium text-sm">💝 {garment.giftFrom}</p>
                </div>
              )}
            </div>

            {garment.colors.length > 0 && (
              <div>
                <p className="text-xs text-gray-400 mb-1.5">Colors</p>
                <div className="flex flex-wrap gap-1.5">
                  {garment.colors.map(c => <Chip key={c} label={c} color="bg-pink-50 text-pink-700 dark:bg-pink-900/20 dark:text-pink-300" />)}
                </div>
              </div>
            )}
            {garment.seasons.length > 0 && (
              <div>
                <p className="text-xs text-gray-400 mb-1.5">Seasons</p>
                <div className="flex flex-wrap gap-1.5">
                  {garment.seasons.map(s => <Chip key={s} label={s} color="bg-orange-50 text-orange-700 dark:bg-orange-900/20 dark:text-orange-300" />)}
                </div>
              </div>
            )}
            {garment.occasionTags.length > 0 && (
              <div>
                <p className="text-xs text-gray-400 mb-1.5">Occasions</p>
                <div className="flex flex-wrap gap-1.5">
                  {garment.occasionTags.map(t => <Chip key={t} label={t} color="bg-purple-50 text-purple-700 dark:bg-purple-900/20 dark:text-purple-300" />)}
                </div>
              </div>
            )}
          </div>

          {/* Wear history */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <p className="font-semibold text-sm mb-3">
              Wear history
              <span className="ml-2 text-xs font-normal text-gray-400">({wears.length} times)</span>
            </p>
            {wears.length === 0 ? (
              <p className="text-sm text-gray-400">Not worn yet — tap "Worn today" to start tracking</p>
            ) : (
              <div className="space-y-1 max-h-40 overflow-y-auto">
                {wears.map(w => (
                  <div key={w.id} className="flex items-center text-sm text-gray-600 dark:text-gray-300 gap-2">
                    <span className="text-gray-300">📅</span>
                    {new Date(w.worn_on).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" })}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      ) : (
        /* ─── Edit mode ─── */
        <div className="mx-4 space-y-3">
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <label className="text-xs text-gray-500">Name</label>
            <input
              value={editName}
              onChange={e => setEditName(e.target.value)}
              className="mt-1 w-full px-3 py-2 rounded-xl bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 text-sm focus:outline-none"
            />
          </div>

          {/* Category chips */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-2">Category</p>
            <div className="flex flex-wrap gap-2">
              {GARMENT_CATEGORIES.map(c => (
                <button key={c} type="button" onClick={() => setEditCategory(c)}
                  className={`px-3 py-1.5 rounded-full text-sm font-medium ${editCategory === c ? "bg-rose-400 text-white" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"}`}
                >
                  {CATEGORY_LABELS[c] || c}
                </button>
              ))}
            </div>
          </div>

          {/* Size chips */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-2">Size</p>
            <div className="flex flex-wrap gap-2">
              {GARMENT_SIZE_ORDER.map(s => (
                <button key={s} type="button" onClick={() => setEditSize(s)}
                  className={`px-3 py-1.5 rounded-full text-sm font-medium ${editSize === s ? "bg-rose-400 text-white" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"}`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          {/* Status */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-2">Status</p>
            <div className="flex flex-wrap gap-2">
              {STATUS_FLOW.map(s => (
                <button key={s} type="button" onClick={() => setEditStatus(s)}
                  className={`px-3 py-1.5 rounded-full text-sm font-medium ${editStatus === s ? "bg-rose-400 text-white" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"}`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          {/* Colors */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-2">Colors</p>
            <div className="flex flex-wrap gap-2 mb-2">
              {editColors.map(c => (
                <button key={c} type="button" onClick={() => setEditColors(editColors.filter(x => x !== c))}
                  className="px-2.5 py-1 rounded-full text-xs bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300"
                >
                  {c} ×
                </button>
              ))}
            </div>
            <div className="flex gap-2">
              <input value={editColorInput} onChange={e => setEditColorInput(e.target.value)}
                onKeyDown={e => { if (e.key === "Enter") { const c = editColorInput.trim().toLowerCase(); if (c && !editColors.includes(c)) setEditColors([...editColors, c]); setEditColorInput(""); }}}
                placeholder="Add color…" 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 type="button" onClick={() => { const c = editColorInput.trim().toLowerCase(); if (c && !editColors.includes(c)) setEditColors([...editColors, c]); setEditColorInput(""); }}
                className="px-3 py-1.5 bg-rose-400 text-white rounded-xl text-sm">Add</button>
            </div>
          </div>

          {/* Seasons */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-2">Seasons</p>
            <div className="flex gap-2">
              {["summer", "monsoon", "winter"].map(s => (
                <button key={s} type="button" onClick={() => setEditSeasons(toggleArray(editSeasons, s))}
                  className={`px-3 py-1.5 rounded-full text-sm font-medium ${editSeasons.includes(s) ? "bg-rose-400 text-white" : "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"}`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          {/* Occasions */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <p className="text-xs text-gray-500 mb-2">Occasions</p>
            <div className="flex flex-wrap gap-2">
              {["everyday", "daycare", "festive", "photoshoot"].map(o => (
                <button key={o} type="button" onClick={() => setEditOccasions(toggleArray(editOccasions, o))}
                  className={`px-3 py-1.5 rounded-full text-sm font-medium ${editOccasions.includes(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={saveEdit} loading={saving} size="lg">Save Changes</Button>
        </div>
      )}
    </div>
  );
}
