"use client";

import { useState, useEffect, useCallback } from "react";
import { Heart, Trash2, Search, Clock, Copy, Check } from "lucide-react";
import { toast } from "sonner";
import { PLATFORM_CONFIGS } from "@/types";
import type { PromptHistory } from "@/types";
import { formatDate, copyToClipboard } from "@/lib/utils";
import { cn } from "@/lib/utils";

export function PromptHistoryTab() {
  const [history, setHistory]           = useState<PromptHistory[]>([]);
  const [loading, setLoading]           = useState(true);
  const [filter, setFilter]             = useState<string>("all");
  const [favoritesOnly, setFavoritesOnly] = useState(false);
  const [search, setSearch]             = useState("");
  const [copiedId, setCopiedId]         = useState<string | null>(null);

  const fetchHistory = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (filter !== "all") params.set("platform", filter);
      if (favoritesOnly) params.set("favorites", "true");
      const res  = await fetch(`/api/history?${params}`);
      const data = await res.json();
      setHistory(data.data ?? []);
    } catch {
      toast.error("Gagal memuat history");
    } finally {
      setLoading(false);
    }
  }, [filter, favoritesOnly]);

  useEffect(() => { fetchHistory(); }, [fetchHistory]);

  async function toggleFavorite(id: string, current: boolean) {
    try {
      const res = await fetch("/api/history", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id, is_favorite: !current }),
      });
      if (res.ok) {
        setHistory((prev) => prev.map((h) => h.id === id ? { ...h, is_favorite: !current } : h));
        toast.success(current ? "Dihapus dari favorit" : "Ditambahkan ke favorit ❤️");
      }
    } catch { toast.error("Gagal update favorit"); }
  }

  async function deleteHistory(id: string) {
    if (!confirm("Hapus history ini?")) return;
    try {
      const res = await fetch(`/api/history?id=${id}`, { method: "DELETE" });
      if (res.ok) {
        setHistory((prev) => prev.filter((h) => h.id !== id));
        toast.success("History dihapus");
      }
    } catch { toast.error("Gagal hapus history"); }
  }

  async function handleCopy(item: PromptHistory) {
    await copyToClipboard(item.output_text ?? "");
    setCopiedId(item.id);
    toast.success("Prompt disalin!");
    setTimeout(() => setCopiedId(null), 2000);
  }

  const filtered = history.filter((h) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (
      h.output_text?.toLowerCase().includes(q) ||
      h.title?.toLowerCase().includes(q) ||
      h.platform.includes(q)
    );
  });

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Cari prompt..."
            className="w-full pl-9 pr-4 py-2 rounded-lg bg-card border border-border focus:border-primary focus:outline-none text-sm"
          />
        </div>
        <select
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
          className="px-3 py-2 rounded-lg bg-card border border-border focus:border-primary focus:outline-none text-sm"
        >
          <option value="all">Semua Platform</option>
          {Object.values(PLATFORM_CONFIGS).map((p) => (
            <option key={p.id} value={p.id}>{p.name}</option>
          ))}
        </select>
        <button
          onClick={() => setFavoritesOnly(!favoritesOnly)}
          className={cn(
            "flex items-center gap-2 px-3 py-2 rounded-lg border text-sm transition-colors",
            favoritesOnly
              ? "bg-pink-500/20 border-pink-500/50 text-pink-400"
              : "bg-card border-border text-muted-foreground hover:text-foreground"
          )}
        >
          <Heart className={cn("w-4 h-4", favoritesOnly && "fill-current")} />
          Favorit
        </button>
      </div>

      {loading ? (
        <div className="space-y-3">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-24 rounded-xl bg-card border border-border animate-pulse" />
          ))}
        </div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-16 text-muted-foreground">
          <Clock className="w-12 h-12 mx-auto mb-3 opacity-30" />
          <p className="font-medium">Belum ada history</p>
          <p className="text-sm mt-1">Generate prompt pertamamu sekarang!</p>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map((item) => {
            const platform = PLATFORM_CONFIGS[item.platform as keyof typeof PLATFORM_CONFIGS];
            return (
              <div key={item.id} className="glass-card rounded-xl p-4 hover:border-border/80 transition-colors">
                <div className="flex items-start gap-3">
                  <span className="text-2xl flex-shrink-0">{platform?.icon ?? "🤖"}</span>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-xs px-2 py-0.5 rounded-full bg-accent text-muted-foreground">
                        {platform?.name}
                      </span>
                      <span className="text-xs text-muted-foreground capitalize">{item.mode}</span>
                      <span className="text-xs text-muted-foreground ml-auto">{formatDate(item.created_at)}</span>
                    </div>
                    <p className="text-sm leading-relaxed line-clamp-2 text-foreground/80">
                      {item.output_text ?? item.title ?? "Prompt tanpa teks"}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-1 mt-3 pt-3 border-t border-border/50">
                  <button
                    onClick={() => handleCopy(item)}
                    className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
                  >
                    {copiedId === item.id
                      ? <><Check className="w-3.5 h-3.5 text-green-400" />Disalin</>
                      : <><Copy className="w-3.5 h-3.5" />Salin</>}
                  </button>
                  <button
                    onClick={() => toggleFavorite(item.id, item.is_favorite)}
                    className={cn(
                      "flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs transition-colors",
                      item.is_favorite
                        ? "text-pink-400 hover:bg-pink-500/10"
                        : "text-muted-foreground hover:text-foreground hover:bg-accent"
                    )}
                  >
                    <Heart className={cn("w-3.5 h-3.5", item.is_favorite && "fill-current")} />
                    {item.is_favorite ? "Favorit" : "Simpan"}
                  </button>
                  <button
                    onClick={() => deleteHistory(item.id)}
                    className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs text-muted-foreground hover:text-red-400 hover:bg-red-500/10 transition-colors ml-auto"
                  >
                    <Trash2 className="w-3.5 h-3.5" />Hapus
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
