"use client";

import { useState } from "react";
import { AlertTriangle, CheckCircle2, RotateCcw, StickyNote, Trash2, XCircle } from "lucide-react";
import { toast } from "sonner";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { useT, useLocale } from "@/shared/i18n/client";
import ConfirmationDialog from "@/presentation/components/shared/confirmation-dialog";
import { Badge } from "@/presentation/components/ui/badge";
import { Button } from "@/presentation/components/ui/button";
import { Textarea } from "@/presentation/components/ui/textarea";
import { Tabs, TabsList, TabsTrigger } from "@/presentation/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/presentation/components/ui/table";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/presentation/components/ui/sheet";
import type { DonnaCorrection, DonnaCorrectionDecision, DonnaCorrectionDetail, DonnaCorrectionStatus } from "@/domain/entities/donna";

type StatusFilter = DonnaCorrectionStatus | "all";

const STATUS_STYLE: Record<DonnaCorrectionStatus, string> = {
  pending: "bg-amber-100 text-amber-800 hover:bg-amber-100",
  confirmed: "bg-green-100 text-green-700 hover:bg-green-100",
  rejected: "bg-red-100 text-red-700 hover:bg-red-100",
};

/** What clients corrected in the agents' answers, one tab per agent: the admin validates, edits, annotates or deletes. */
export default function DonnaCorrectionsTab() {
  const t = useT();
  const locale = useLocale();
  const c = t.donnaCorrections;
  const repo = useRepositories().donnaRepository;
  const [agent, setAgent] = useState<string>("all");
  const [status, setStatus] = useState<StatusFilter>("pending");
  const [open, setOpen] = useState<DonnaCorrection | null>(null);

  const { data, loading, refetch } = useApiQuery(
    () => repo.getCorrections({ status, agent: agent === "all" ? undefined : agent }),
    { deps: [status, agent] }
  );

  const agentName = (id: string) => (c.agents as Record<string, string>)[id] ?? id;
  const mistake = (type: string) => (c.mistakeTypes as Record<string, string>)[type] ?? type;
  const date = (value: string) =>
    new Intl.DateTimeFormat(locale === "fr" ? "fr-FR" : "en-GB", { dateStyle: "short", timeStyle: "short" }).format(new Date(value));
  const totalPending = (data?.agents ?? []).reduce((sum, item) => sum + item.counts.pending, 0);
  const items = data?.items ?? [];

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-3">
        <Tabs value={agent} onValueChange={setAgent}>
          <TabsList className="h-auto flex-wrap">
            <TabsTrigger value="all">
              {c.allAgents}
              {totalPending > 0 && <PendingCount value={totalPending} />}
            </TabsTrigger>
            {(data?.agents ?? []).map((item) => (
              <TabsTrigger key={item.agent} value={item.agent} title={item.reachable ? undefined : c.unreachable}>
                {agentName(item.agent)}
                {item.reachable ? item.counts.pending > 0 && <PendingCount value={item.counts.pending} /> : <AlertTriangle className="ml-1.5 h-3.5 w-3.5 text-amber-600" />}
              </TabsTrigger>
            ))}
          </TabsList>
        </Tabs>
        <Tabs value={status} onValueChange={(value) => setStatus(value as StatusFilter)}>
          <TabsList>
            {(["pending", "confirmed", "rejected", "all"] as const).map((value) => (
              <TabsTrigger key={value} value={value}>{c.status[value]}</TabsTrigger>
            ))}
          </TabsList>
        </Tabs>
      </div>

      {(data?.agents ?? []).some((item) => !item.reachable) && (
        <p className="flex items-center gap-2 text-sm text-amber-700">
          <AlertTriangle className="h-4 w-4" />
          {c.unreachable} : {(data?.agents ?? []).filter((item) => !item.reachable).map((item) => agentName(item.agent)).join(", ")}
        </p>
      )}

      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{c.columns.date}</TableHead>
              <TableHead>{c.columns.agent}</TableHead>
              <TableHead>{c.columns.type}</TableHead>
              <TableHead>{c.columns.asked}</TableHead>
              <TableHead>{c.columns.answered}</TableHead>
              <TableHead>{c.columns.rule}</TableHead>
              <TableHead>{c.columns.status}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading && items.length === 0 ? (
              <TableRow><TableCell colSpan={7} className="py-10 text-center text-muted-foreground">…</TableCell></TableRow>
            ) : items.length === 0 ? (
              <TableRow><TableCell colSpan={7} className="py-10 text-center text-muted-foreground">{c.empty}</TableCell></TableRow>
            ) : (
              items.map((item) => (
                <TableRow key={`${item.agent}-${item.id}`} className="cursor-pointer" onClick={() => setOpen(item)}>
                  <TableCell className="whitespace-nowrap">{date(item.timestamp)}</TableCell>
                  <TableCell><Badge variant="secondary">{agentName(item.agent)}</Badge></TableCell>
                  <TableCell className="whitespace-nowrap text-sm">{mistake(item.mistake_type)}</TableCell>
                  <TableCell><p className="line-clamp-2 max-w-xs">{item.user_message_raw}</p></TableCell>
                  <TableCell><p className="line-clamp-2 max-w-xs text-muted-foreground">{item.agent_wrong_response}</p></TableCell>
                  <TableCell><p className="line-clamp-2 max-w-xs">{item.correction_summary}</p></TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Badge className={STATUS_STYLE[item.status]}>{c.statusOne[item.status]}</Badge>
                      {item.notes && <StickyNote className="h-4 w-4 text-muted-foreground" aria-label={c.hasNotes} />}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <CorrectionSheet
        correction={open}
        agentName={agentName}
        mistake={mistake}
        date={date}
        onClose={() => setOpen(null)}
        onChanged={() => void refetch()}
      />
    </div>
  );
}

function PendingCount({ value }: { value: number }) {
  return <span className="ml-1.5 rounded-full bg-amber-500 px-1.5 text-xs font-semibold text-white">{value}</span>;
}

interface CorrectionSheetProps {
  correction: DonnaCorrection | null;
  agentName: (id: string) => string;
  mistake: (type: string) => string;
  date: (value: string) => string;
  onClose: () => void;
  onChanged: () => void;
}

function CorrectionSheet({ correction, agentName, mistake, date, onClose, onChanged }: CorrectionSheetProps) {
  const t = useT();
  const c = t.donnaCorrections;
  const repo = useRepositories().donnaRepository;
  const [confirmDelete, setConfirmDelete] = useState(false);

  const { data: detail, refetch } = useApiQuery<DonnaCorrectionDetail | null>(
    () => (correction ? repo.getCorrection(correction.agent, correction.id) : Promise.resolve(null)),
    { deps: [correction?.agent, correction?.id] }
  );
  const shown = detail ?? correction;

  const remove = useApiMutation(() => repo.deleteCorrection(correction!.agent, correction!.id), {
    successMessage: c.toasts.deleted,
    onSuccess: () => { setConfirmDelete(false); onChanged(); onClose(); },
  });

  return (
    <>
      <Sheet open={correction !== null} onOpenChange={(value) => !value && onClose()}>
        <SheetContent className="w-full overflow-y-auto sm:max-w-xl">
          {shown && (
            <>
              <SheetHeader className="px-6 pt-6">
                <SheetTitle>{mistake(shown.mistake_type)}</SheetTitle>
                <SheetDescription>{[agentName(shown.agent), date(shown.timestamp)].join(" · ")}</SheetDescription>
              </SheetHeader>
              <div className="space-y-5 px-6 pb-6">
                <div className="flex flex-wrap items-center gap-2">
                  <Badge className={STATUS_STYLE[shown.status]}>{c.statusOne[shown.status]}</Badge>
                  <Badge variant="secondary">{agentName(shown.agent)}</Badge>
                </div>
                <Block title={c.detail.asked} text={shown.user_message_raw} />
                <Block title={c.detail.answered} text={shown.agent_wrong_response} muted />
                {detail?.correction_followup_message && <Block title={c.detail.followup} text={detail.correction_followup_message} />}
                {detail?.conversation_context && <Block title={c.detail.context} text={detail.conversation_context} muted />}
                {detail?.user_message_pattern && <p className="text-xs text-muted-foreground">{c.detail.pattern} : {detail.user_message_pattern}</p>}

                {/* Remounted when the saved correction changes, so the fields always start from it. */}
                <CorrectionEditor
                  key={`${shown.agent}-${shown.id}-${shown.status}-${shown.correction_summary}-${shown.notes}`}
                  correction={shown}
                  onSaved={() => { onChanged(); void refetch(); }}
                  onDelete={() => setConfirmDelete(true)}
                  deleting={remove.loading}
                />
              </div>
            </>
          )}
        </SheetContent>
      </Sheet>
      <ConfirmationDialog
        open={confirmDelete}
        onOpenChange={setConfirmDelete}
        title={c.deleteTitle}
        description={c.deleteDescription}
        confirmLabel={c.actions.delete}
        variant="destructive"
        loading={remove.loading}
        onConfirm={() => void remove.mutate(undefined)}
      />
    </>
  );
}

function CorrectionEditor({ correction, onSaved, onDelete, deleting }: { correction: DonnaCorrection; onSaved: () => void; onDelete: () => void; deleting: boolean }) {
  const t = useT();
  const c = t.donnaCorrections;
  const repo = useRepositories().donnaRepository;
  const [summary, setSummary] = useState(correction.correction_summary);
  const [notes, setNotes] = useState(correction.notes);

  const update = useApiMutation(
    (decision: DonnaCorrectionDecision | undefined) =>
      repo.updateCorrection(correction.agent, correction.id, {
        decision,
        ...(summary.trim() ? { correction_summary: summary.trim() } : {}),
        notes,
      }),
    { onSuccess: onSaved }
  );

  const act = async (decision?: DonnaCorrectionDecision) => {
    const saved = await update.mutate(decision);
    if (saved) toast.success(decision ? c.toasts[decision] : c.toasts.saved);
  };

  return (
    <>
      <section className="space-y-1">
        <h3 className="text-sm font-semibold">{c.detail.rule}</h3>
        <p className="text-xs text-muted-foreground">{c.detail.ruleHint}</p>
        <Textarea value={summary} onChange={(e) => setSummary(e.target.value)} rows={4} />
      </section>
      <section className="space-y-1">
        <h3 className="text-sm font-semibold">{c.detail.notes}</h3>
        <p className="text-xs text-muted-foreground">{c.detail.notesHint}</p>
        <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} />
      </section>

      <div className="flex flex-wrap gap-2">
        {correction.status !== "confirmed" && (
          <Button size="sm" className="bg-green-600 hover:bg-green-700" disabled={update.loading || !summary.trim()} onClick={() => act("confirm")}>
            <CheckCircle2 className="mr-1 h-4 w-4" />{c.actions.confirm}
          </Button>
        )}
        {correction.status !== "rejected" && (
          <Button size="sm" variant="outline" className="text-red-600" disabled={update.loading} onClick={() => act("reject")}>
            <XCircle className="mr-1 h-4 w-4" />{c.actions.reject}
          </Button>
        )}
        {correction.status !== "pending" && (
          <Button size="sm" variant="outline" disabled={update.loading} onClick={() => act("pending")}>
            <RotateCcw className="mr-1 h-4 w-4" />{c.actions.reopen}
          </Button>
        )}
        <Button size="sm" variant="outline" disabled={update.loading || !summary.trim()} onClick={() => act()}>
          {c.actions.save}
        </Button>
        <Button size="sm" variant="ghost" className="ml-auto text-red-600" disabled={deleting} onClick={onDelete}>
          <Trash2 className="mr-1 h-4 w-4" />{c.actions.delete}
        </Button>
      </div>
    </>
  );
}

function Block({ title, text, muted = false }: { title: string; text: string; muted?: boolean }) {
  return (
    <section>
      <h3 className="mb-1 text-sm font-semibold">{title}</h3>
      <p className={`whitespace-pre-wrap rounded-md p-3 text-sm ${muted ? "bg-muted/50 text-muted-foreground" : "bg-muted"}`}>{text}</p>
    </section>
  );
}
