"use client";

import { useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/app-shell";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import {
  useMissingPrecedents,
  type MissingPrecedentStatus,
} from "@/lib/api/missing-precedents";
import { MissingPrecedentsTable } from "@/components/missing-precedents/missing-precedents-table";

/**
 * Missing-precedents page (TaskMaster #35).
 *
 * Surfaces citations that party briefs invoke but which aren't yet in the
 * precedent_library. Four tabs by status; each tab uses the same table
 * component with a different filter. Drawer (sheet) opens on row click
 * with metadata + upload form that routes to internal_decision_upload
 * (ערר/בל"מ citations) or precedent_library_upload (court rulings).
 */
function StatusBadge({ status, count }: { status: MissingPrecedentStatus; count: number }) {
  if (!count) return null;
  const variants: Record<MissingPrecedentStatus, string> = {
    open: "bg-gold-wash text-gold-deep border-gold/40",
    uploaded: "bg-rule-soft text-ink-muted border-rule",
    closed: "bg-emerald-50 text-emerald-800 border-emerald-300/60",
    irrelevant: "bg-rule-soft text-ink-muted border-rule",
  };
  return (
    <Badge
      variant="outline"
      className={`ms-1 text-[0.65rem] ${variants[status]}`}
    >
      {count}
    </Badge>
  );
}

export default function MissingPrecedentsPage() {
  const [caseNumber, setCaseNumber] = useState("");
  const [legalTopic, setLegalTopic] = useState("");

  const counts = useMissingPrecedents({ limit: 1 });
  const byStatus = counts.data?.by_status ?? {};

  return (
    <AppShell>
      <section className="space-y-6">
        <header>
          <nav className="text-[0.78rem] text-ink-muted mb-1">
            <Link href="/" className="hover:text-gold-deep">בית</Link>
            <span aria-hidden> · </span>
            <span className="text-navy">פסיקה חסרה בקורפוס</span>
          </nav>
          <h1 className="text-navy mb-0">פסיקה חסרה בקורפוס</h1>
          <p className="text-ink-muted text-sm mt-1 max-w-3xl">
            פסיקות שצוטטו בכתבי הטענות אך אינן עדיין בקורפוס. סוכן המחקר רושם
            פערים אוטומטית; היו&quot;ר סוגר אותם על־ידי העלאת המסמך — ניתוב
            אוטומטי בין הקורפוס הסמכותי (פסקי דין) להחלטות ועדות ערר.
          </p>
        </header>

        <div className="h-[2px] bg-gradient-to-l from-transparent via-gold to-transparent" />

        <Card className="bg-surface border-rule shadow-sm">
          <CardContent className="px-6 py-5 space-y-5">
            {/* Shared filters */}
            <div className="flex items-end gap-3 flex-wrap">
              <div className="flex-1 min-w-[200px]">
                <label className="text-[0.78rem] text-ink-muted">תיק (מספר ערר)</label>
                <Input
                  value={caseNumber}
                  onChange={(e) => setCaseNumber(e.target.value)}
                  placeholder="1017-03-26"
                  dir="rtl"
                />
              </div>
              <div className="flex-1 min-w-[200px]">
                <label className="text-[0.78rem] text-ink-muted">נושא משפטי</label>
                <Input
                  value={legalTopic}
                  onChange={(e) => setLegalTopic(e.target.value)}
                  placeholder="זכות עמידה"
                  dir="rtl"
                />
              </div>
            </div>

            <Tabs defaultValue="open" dir="rtl">
              <TabsList className="bg-rule-soft/60">
                <TabsTrigger value="open">
                  פתוחות
                  <StatusBadge status="open" count={byStatus.open ?? 0} />
                </TabsTrigger>
                <TabsTrigger value="uploaded">
                  הועלו
                  <StatusBadge status="uploaded" count={byStatus.uploaded ?? 0} />
                </TabsTrigger>
                <TabsTrigger value="closed">
                  נסגרו
                  <StatusBadge status="closed" count={byStatus.closed ?? 0} />
                </TabsTrigger>
                <TabsTrigger value="irrelevant">
                  לא רלוונטי
                  <StatusBadge
                    status="irrelevant"
                    count={byStatus.irrelevant ?? 0}
                  />
                </TabsTrigger>
                <TabsTrigger value="all">הכל</TabsTrigger>
              </TabsList>

              <TabsContent value="open" className="mt-4">
                <MissingPrecedentsTable
                  status="open"
                  caseNumber={caseNumber.trim() || undefined}
                  legalTopic={legalTopic.trim() || undefined}
                />
              </TabsContent>

              <TabsContent value="uploaded" className="mt-4">
                <MissingPrecedentsTable
                  status="uploaded"
                  caseNumber={caseNumber.trim() || undefined}
                  legalTopic={legalTopic.trim() || undefined}
                />
              </TabsContent>

              <TabsContent value="closed" className="mt-4">
                <MissingPrecedentsTable
                  status="closed"
                  caseNumber={caseNumber.trim() || undefined}
                  legalTopic={legalTopic.trim() || undefined}
                />
              </TabsContent>

              <TabsContent value="irrelevant" className="mt-4">
                <MissingPrecedentsTable
                  status="irrelevant"
                  caseNumber={caseNumber.trim() || undefined}
                  legalTopic={legalTopic.trim() || undefined}
                />
              </TabsContent>

              <TabsContent value="all" className="mt-4">
                <MissingPrecedentsTable
                  caseNumber={caseNumber.trim() || undefined}
                  legalTopic={legalTopic.trim() || undefined}
                />
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
      </section>
    </AppShell>
  );
}
