"use client";

import { use } 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 { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { CaseHeader } from "@/components/cases/case-header";
import { CaseEditDialog } from "@/components/cases/case-edit-dialog";
import { WorkflowTimeline } from "@/components/cases/workflow-timeline";
import { StatusGuide } from "@/components/cases/status-guide";
import { StatusChanger } from "@/components/cases/status-changer";
import { DocumentsPanel } from "@/components/cases/documents-panel";
import { DraftsPanel } from "@/components/cases/drafts-panel";
import { LegalArgumentsPanel } from "@/components/cases/legal-arguments-panel";
import { AgentActivityFeed } from "@/components/cases/agent-activity-feed";
import { AgentStatusWidget } from "@/components/cases/agent-status-widget";
import { UploadSheet } from "@/components/documents/upload-sheet";
import { expectedOutcomes } from "@/lib/schemas/case";
import { useCase, useStartWorkflow } from "@/lib/api/cases";
import { toast } from "sonner";
import { Play, Loader2 } from "lucide-react";

const EXPECTED_OUTCOME_LABELS: Record<string, string> = Object.fromEntries(
  expectedOutcomes.map((o) => [o.value, o.label]),
);

/*
 * Next 16 breaking change: route params are now a Promise.
 * The `use()` hook unwraps them inside a client component.
 */
export default function CaseDetailPage({
  params,
}: {
  params: Promise<{ caseNumber: string }>;
}) {
  const { caseNumber } = use(params);
  const { data, isPending, error } = useCase(caseNumber);
  const startWorkflow = useStartWorkflow(caseNumber);
  const canStartWorkflow = data?.status === "new" || data?.status === "documents_ready";
  const expectedOutcomeLabel = data?.expected_outcome
    ? EXPECTED_OUTCOME_LABELS[data.expected_outcome] ?? data.expected_outcome
    : null;

  return (
    <AppShell>
      <section className="space-y-6">
        {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="/">חזרה לרשימת התיקים</Link>
              </Button>
            </CardContent>
          </Card>
        ) : (
          <>
            {isPending ? (
              <Card className="bg-surface border-rule shadow-sm">
                <CardContent className="px-6 py-5 space-y-3">
                  <Skeleton className="h-4 w-40" />
                  <Skeleton className="h-8 w-64" />
                  <Skeleton className="h-6 w-96" />
                </CardContent>
              </Card>
            ) : (
              <CaseHeader data={data} />
            )}

            <div className="grid gap-6 lg:grid-cols-[1fr_280px]">
              <Card className="bg-surface border-rule shadow-sm">
                <CardContent className="px-6 py-5">
                  <Tabs defaultValue="overview" dir="rtl">
                    <div className="flex items-center justify-between gap-3 mb-1 flex-wrap">
                      <TabsList className="bg-rule-soft/60">
                        <TabsTrigger value="overview">סקירה</TabsTrigger>
                        <TabsTrigger value="arguments">
                          טיעונים
                        </TabsTrigger>
                        <TabsTrigger value="drafts">
                          טיוטות והערות
                        </TabsTrigger>
                        <TabsTrigger value="agents">
                          סוכנים
                        </TabsTrigger>
                      </TabsList>
                      <div className="flex items-center gap-2 flex-wrap">
                        <Button asChild className="bg-navy hover:bg-navy-soft text-parchment">
                          <Link href={`/cases/${caseNumber}/compose`}>
                            פתח בעורך ההחלטה
                          </Link>
                        </Button>
                        {data && <CaseEditDialog data={data} />}
                        <UploadSheet caseNumber={caseNumber} />
                      </div>
                    </div>

                    <TabsContent value="overview" className="mt-5 space-y-4">
                      <div>
                        <h3 className="text-navy text-base mb-2">תוצאה צפויה</h3>
                        <p className="text-ink-soft text-sm leading-relaxed">
                          {expectedOutcomeLabel ?? "לא נקבעה תוצאה צפויה."}
                        </p>
                      </div>
                      <div>
                        <h3 className="text-navy text-base mb-2">סיכום מהיר</h3>
                        <dl className="grid grid-cols-2 gap-y-2 gap-x-6 text-sm">
                          <dt className="text-ink-muted">בעיבוד</dt>
                          <dd className="text-ink tabular-nums">
                            {data?.processing_count ?? 0}
                          </dd>
                        </dl>
                      </div>
                      {canStartWorkflow && (
                        <div className="pt-2 border-t border-rule">
                          <Button
                            className="bg-gold-deep hover:bg-gold-deep/90 text-parchment"
                            disabled={startWorkflow.isPending}
                            onClick={() =>
                              startWorkflow.mutate(undefined, {
                                onSuccess: (res) =>
                                  toast.success(
                                    `תהליך הופעל — ${res.issue_identifier}`,
                                  ),
                                onError: (err) =>
                                  toast.error(`שגיאה: ${err.message}`),
                              })
                            }
                          >
                            {startWorkflow.isPending ? (
                              <Loader2 className="w-4 h-4 animate-spin me-1.5" />
                            ) : (
                              <Play className="w-4 h-4 me-1.5" />
                            )}
                            התחל תהליך
                          </Button>
                        </div>
                      )}
                      <DocumentsPanel data={data} />
                    </TabsContent>

                    <TabsContent value="arguments" className="mt-5">
                      <LegalArgumentsPanel caseNumber={caseNumber} />
                    </TabsContent>

                    <TabsContent value="drafts" className="mt-5">
                      <DraftsPanel
                        caseNumber={caseNumber}
                        status={data?.status}
                      />
                    </TabsContent>

                    <TabsContent value="agents" className="mt-5">
                      <AgentActivityFeed caseNumber={caseNumber} />
                    </TabsContent>
                  </Tabs>
                </CardContent>
              </Card>

              <Card className="bg-surface border-rule shadow-sm h-fit">
                <CardContent className="px-6 py-5 space-y-5">
                  <AgentStatusWidget caseNumber={caseNumber} />
                  <h2 className="text-navy text-base mb-4">שלב בתהליך</h2>
                  <WorkflowTimeline status={data?.status} />
                  <StatusChanger caseNumber={caseNumber} currentStatus={data?.status} />
                  <StatusGuide />
                </CardContent>
              </Card>
            </div>
          </>
        )}
      </section>
    </AppShell>
  );
}
