"use client";

import { use, useState } from "react";
import Link from "next/link";
import { Pencil } from "lucide-react";
import { AppShell } from "@/components/app-shell";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { usePrecedent } from "@/lib/api/precedent-library";
import { PrecedentEditSheet } from "@/components/precedents/precedent-edit-sheet";
import { ExtractedHalachotSection } from "@/components/precedents/extracted-halachot";
import { RelatedCasesSection } from "@/components/precedents/link-related-dialog";

const PRACTICE_AREA_LABELS: Record<string, string> = {
  rishuy_uvniya: "רישוי ובנייה",
  betterment_levy: "היטל השבחה",
  compensation_197: "פיצויים (197)",
};

const SOURCE_TYPE_LABELS: Record<string, string> = {
  court_ruling: "פסק דין",
  appeals_committee: "ועדת ערר",
};

/* Next 16 breaking change: route params are now a Promise.
 * The `use()` hook unwraps them inside a client component. */
export default function PrecedentDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const [editing, setEditing] = useState(false);
  const { data, isPending, error } = usePrecedent(id);

  return (
    <AppShell>
      <section className="space-y-6" dir="rtl">
        <header>
          <nav className="text-[0.78rem] text-ink-muted mb-1">
            <Link href="/" className="hover:text-gold-deep">בית</Link>
            <span aria-hidden> · </span>
            <Link href="/precedents" className="hover:text-gold-deep">ספריית פסיקה</Link>
            <span aria-hidden> · </span>
            <span className="text-navy">פרטי פסיקה</span>
          </nav>
        </header>

        {error ? (
          <Card className="bg-danger-bg border-danger/40">
            <CardContent className="px-6 py-6 text-center space-y-3">
              <p className="text-danger font-semibold">שגיאה בטעינת הפסיקה</p>
              <p className="text-sm text-ink-muted">{error.message}</p>
              <Button asChild variant="outline">
                <Link href="/precedents">חזרה לספרייה</Link>
              </Button>
            </CardContent>
          </Card>
        ) : isPending || !data ? (
          <div className="space-y-3">
            {[...Array(5)].map((_, i) => <Skeleton key={i} className="h-16 w-full" />)}
          </div>
        ) : (
          <>
            <Card className="bg-surface border-rule shadow-sm">
              <CardContent className="px-6 py-5 space-y-4">
                <div className="flex items-start justify-between gap-3 flex-wrap">
                  <div className="min-w-0 flex-1">
                    <h1 className="text-navy text-2xl font-semibold mb-1 leading-tight">
                      {data.case_name || "—"}
                    </h1>
                    <div className="text-ink-muted text-sm font-mono" dir="ltr">
                      {data.case_number}
                    </div>
                  </div>
                  <Button variant="outline" size="sm" onClick={() => setEditing(true)}>
                    <Pencil className="w-3.5 h-3.5 me-1" /> ערוך פרטים
                  </Button>
                </div>

                <div className="flex items-center gap-2 flex-wrap">
                  {data.practice_area ? (
                    <Badge variant="outline" className="text-[0.7rem]">
                      {PRACTICE_AREA_LABELS[data.practice_area] ?? data.practice_area}
                    </Badge>
                  ) : null}
                  {data.source_type ? (
                    <Badge variant="outline" className="text-[0.7rem]">
                      {SOURCE_TYPE_LABELS[data.source_type] ?? data.source_type}
                    </Badge>
                  ) : null}
                  {data.precedent_level ? (
                    <Badge variant="outline" className="text-[0.7rem]">
                      {data.precedent_level}
                    </Badge>
                  ) : null}
                  {data.is_binding ? (
                    <Badge
                      variant="outline"
                      className="text-[0.7rem] bg-gold-wash text-gold-deep border-gold/40"
                    >
                      הלכה מחייבת
                    </Badge>
                  ) : null}
                  {data.court ? (
                    <span className="text-[0.78rem] text-ink-muted">{data.court}</span>
                  ) : null}
                  {data.date ? (
                    <span className="text-[0.78rem] text-ink-muted tabular-nums" dir="ltr">
                      {data.date.slice(0, 10)}
                    </span>
                  ) : null}
                </div>

                {data.headnote ? (
                  <div>
                    <h3 className="text-navy text-sm font-semibold m-0 mb-1">Headnote</h3>
                    <p className="text-ink-soft text-sm leading-relaxed m-0">
                      {data.headnote}
                    </p>
                  </div>
                ) : null}

                {data.summary ? (
                  <div>
                    <h3 className="text-navy text-sm font-semibold m-0 mb-1">תקציר</h3>
                    <p className="text-ink-soft text-sm leading-relaxed m-0 whitespace-pre-line">
                      {data.summary}
                    </p>
                  </div>
                ) : null}

                {(data as { key_quote?: string }).key_quote ? (
                  <div>
                    <h3 className="text-navy text-sm font-semibold m-0 mb-1">ציטוט מרכזי</h3>
                    <blockquote className="text-ink-soft text-sm leading-relaxed border-r-2 border-gold pr-3 m-0">
                      {(data as { key_quote?: string }).key_quote}
                    </blockquote>
                  </div>
                ) : null}

                {data.subject_tags?.length ? (
                  <div className="flex items-center gap-1 flex-wrap pt-1">
                    {data.subject_tags.map((t) => (
                      <Badge key={t} variant="outline" className="text-[0.65rem]">
                        {t}
                      </Badge>
                    ))}
                  </div>
                ) : null}
              </CardContent>
            </Card>

            <Card className="bg-surface border-rule shadow-sm">
              <CardContent className="px-6 py-5">
                <RelatedCasesSection
                  caseId={id}
                  related={data.related_cases ?? []}
                />
              </CardContent>
            </Card>

            <Card className="bg-surface border-rule shadow-sm">
              <CardContent className="px-6 py-5">
                <ExtractedHalachotSection halachot={data.halachot ?? []} />
              </CardContent>
            </Card>
          </>
        )}

        <PrecedentEditSheet
          caseLawId={editing ? id : null}
          onOpenChange={(open) => setEditing(open)}
        />
      </section>
    </AppShell>
  );
}
