import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Sparkles, Save, Trash2, Settings } from "lucide-react";
import { useClaims } from "@/hooks/useClaims";
import { SettingsDialog } from "@/components/SettingsDialog";
import type { Claim, ClaimStatus } from "@/lib/types";

/** Generate a stable key from claim content */
function getClaimKey(claim: Claim, index: number): string {
  // Use content hash for stable identity, with index as fallback for duplicates
  return `${claim.subject}-${claim.predicate}-${claim.object}-${index}`;
}

function StatusBadge({ status }: { status: ClaimStatus }) {
  const variants: Record<ClaimStatus, "secondary" | "success" | "warning"> = {
    new: "secondary",
    matches: "success",
    contradicts: "warning",
  };
  const labels: Record<ClaimStatus, string> = {
    new: "New",
    matches: "Matches",
    contradicts: "Contradicts",
  };
  return <Badge variant={variants[status]}>{labels[status]}</Badge>;
}

export default function App() {
  const [settingsOpen, setSettingsOpen] = useState(false);
  const {
    claims,
    inputText,
    extraction,
    setInputText,
    extract,
    save,
    clear,
    isLoading,
  } = useClaims();

  return (
    <main className="min-h-screen p-4 flex flex-col gap-4">
      <header className="text-center relative">
        <Button
          variant="ghost"
          size="icon"
          className="absolute right-0 top-0"
          onClick={() => setSettingsOpen(true)}
        >
          <Settings className="size-4" />
        </Button>
        <h1 className="text-2xl font-bold tracking-tight">disputed.</h1>
        <p className="text-sm text-muted-foreground">
          your knowledge graph, always listening
        </p>
      </header>

      <Card className="flex-1 flex flex-col">
        <CardHeader className="pb-2">
          <CardTitle className="text-sm font-medium">
            Paste text to extract claims
          </CardTitle>
        </CardHeader>
        <CardContent className="flex-1 flex flex-col gap-3">
          <Textarea
            placeholder="Paste an article, transcript, or any text..."
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            className="flex-1 min-h-[120px]"
          />
          {extraction.error && (
            <p className="text-sm text-destructive">{extraction.error}</p>
          )}
          <div className="flex gap-2">
            <Button
              onClick={extract}
              disabled={!inputText.trim() || isLoading}
              className="flex-1"
            >
              <Sparkles className="size-4" />
              {isLoading ? "Processing..." : "Extract Claims"}
            </Button>
          </div>
        </CardContent>
      </Card>

      {claims.length > 0 && (
        <Card>
          <CardHeader className="pb-2 flex-row items-center justify-between">
            <CardTitle className="text-sm font-medium">
              {claims.length} claim{claims.length !== 1 ? "s" : ""} found
            </CardTitle>
            <div className="flex gap-2">
              <Button variant="ghost" size="sm" onClick={clear}>
                <Trash2 className="size-4" />
              </Button>
              <Button size="sm" onClick={save}>
                <Save className="size-4" />
                Save All
              </Button>
            </div>
          </CardHeader>
          <CardContent className="space-y-3">
            {claims.map((check, i) => (
              <div
                key={getClaimKey(check.claim, i)}
                className="p-3 rounded-md bg-secondary/50 space-y-2"
              >
                <div className="flex items-start justify-between gap-2">
                  <p className="text-sm font-medium">
                    <span className="text-primary">{check.claim.subject}</span>{" "}
                    <span className="text-muted-foreground">
                      {check.claim.predicate}
                    </span>{" "}
                    <span className="text-primary">{check.claim.object}</span>
                  </p>
                  <StatusBadge status={check.status} />
                </div>
                <p className="text-xs text-muted-foreground italic">
                  "{check.claim.quote}"
                </p>
                <Badge variant="outline" className="text-xs">
                  {Math.round(check.claim.confidence * 100)}% confidence
                </Badge>
              </div>
            ))}
          </CardContent>
        </Card>
      )}

      <SettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} />
    </main>
  );
}
