'use client';
import { ErrorState } from '@/components/ui/feedback/ErrorState';

/**
 * AdminCaseDetail — admin view for a transaction case.
 * Extends ticket detail with case-specific decision actions.
 */

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { QueryBoundary } from '@platform-modules/ui-primitives';
import { HydratedIsland } from '@/components/HydratedIsland';
import { useT } from '@/lib/i18n/react';
import { SupportThread } from '@/components/ui/domain/support/SupportThread';
import { SupportMessageComposer } from '@/components/ui/domain/support/SupportMessageComposer';
import { AdminRefundDialog } from './internals/AdminRefundDialog';
import { Button } from '@/components/ui/primitives/Button';
import { Badge } from '@/components/ui/primitives/Badge';
import { ConfidenceBar } from '@/components/ui/primitives/ConfidenceBar';
import { CaseDetailSkeleton } from '@/components/ui/feedback/Skeleton';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import { Grid } from '@/components/ui/layout/Grid';
import { Stack } from '@/components/ui/layout/Stack';
import { Row } from '@/components/ui/layout/Row';
import { getCsrfToken } from '@/lib/csrf';
import { formatAgorotShekels } from '@/lib/money';
import { captureCaught } from '@/lib/observability';
import { CaseOfferCard } from '@/components/ui/domain/support/CaseOfferCard';
import type { AIInterventionView, CaseOfferView } from '@/server/support/types';
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogFooter,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogAction,
  AlertDialogCancel,
} from '@/components/ui/overlays/AlertDialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/primitives/Select';
import { Textarea } from '@/components/ui/primitives/Textarea';
import { Label } from '@/components/ui/primitives/Label';
import { ContextPanel } from './internals/ContextPanel';
import { useClaim, useClose, usePostMessage, useDecide } from './internals/useAdminSupport';

interface CaseData {
  id: string;
  status: string;
  assignedAgentId: string | null;
  purchaseId?: string;
  returnId?: string | null;
  customerId?: string;
  vendorId?: string;
  metadata?: Record<string, unknown>;
}

interface PurchaseData {
  totalCents?: number;
}

function aiDecisionLabel(decision: string, tNav: (key: string) => string): string {
  switch (decision) {
    case 'propose':
      return tNav('decision_propose');
    case 'act':
      return tNav('ai_decision_act');
    case 'escalate':
      return tNav('ai_decision_escalate');
    default:
      return decision;
  }
}

function aiRecReason(output: unknown): string {
  return typeof output === 'string' && output.length >= 3 ? output : 'AI recommendation';
}

function aiRecExecuteLabel(toolName: string, tNav: (key: string) => string): string {
  switch (toolName) {
    case 'propose-refund':
      return tNav('ai_rec_refund');
    case 'propose-resolution':
      return tNav('ai_rec_resolve_case');
    case 'propose-return-approve':
      return tNav('ai_rec_approve_return');
    case 'propose-return-deny':
      return tNav('ai_rec_deny_return');
    case 'flag-vendor':
      return tNav('ai_rec_flag_vendor');
    default:
      return tNav('ai_rec_execute');
  }
}

function CaseDetailInner({ caseId }: { caseId: string }) {
  const t = useT('admin');
  const ts = t('support') as unknown as Record<string, string>;
  const tNav = useT('admin_support');
  const tCommon = useT('common');
  const [visibility, setVisibility] = useState<'public' | 'site_internal'>('public');
  const [refundOpen, setRefundOpen] = useState(false);
  const [confirmDeny, setConfirmDeny] = useState(false);
  const [confirmReplacement, setConfirmReplacement] = useState(false);
  const [confirmReturnApprove, setConfirmReturnApprove] = useState(false);
  const [confirmReturnDeny, setConfirmReturnDeny] = useState(false);
  const [confirmReassign, setConfirmReassign] = useState(false);
  const [confirmClose, setConfirmClose] = useState(false);
  const [confirmAiResolve, setConfirmAiResolve] = useState(false);
  const [reassignReason, setReassignReason] = useState('');
  const [actionError, setActionError] = useState<string | null>(null);
  const [aiRecDismissed, setAiRecDismissed] = useState(false);
  const [aiRecExecuting, setAiRecExecuting] = useState(false);
  const [confirmAiOffer, setConfirmAiOffer] = useState(false);
  const [aiOfferExecuting, setAiOfferExecuting] = useState(false);
  const [aiOfferSuccess, setAiOfferSuccess] = useState(false);

  const caseQuery = useQuery({
    queryKey: ['admin-support', 'case', caseId],
    queryFn: () =>
      fetch(`/api/admin/support/cases/${caseId}`).then(
        (r) =>
          r.json() as Promise<{
            ok: boolean;
            case: CaseData;
            purchase?: PurchaseData;
            messages: unknown[];
            attachments: unknown[];
            interventions: unknown[];
            transitions: unknown[];
            offers: CaseOfferView[];
            resolution: { id: string } | null;
            offerExecutions: Record<
              string,
              {
                status: 'pending' | 'processing' | 'failed' | 'completed' | 'decided';
                retryable: boolean;
              }
            >;
          }>,
      ),
    refetchInterval: 15_000,
  });

  const claim = useClaim('case', caseId);
  const close = useClose('case', caseId);
  const postMessage = usePostMessage('case', caseId);
  const decide = useDecide(caseId);

  async function handleDecide(payload: Record<string, unknown>) {
    setActionError(null);
    try {
      await decide.mutateAsync(payload);
      await caseQuery.refetch();
    } catch (err) {
      setActionError(err instanceof Error ? err.message : String(err));
    }
  }

  async function postReturnAction(path: string, body?: Record<string, unknown>) {
    const res = await fetch(path, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-csrf-token': getCsrfToken(),
      },
      body: JSON.stringify(body ?? {}),
    });
    const json = (await res.json().catch((err) => {
      captureCaught(err, { scope: 'AdminCaseDetail.postReturnAction.parseJson' });
      return {};
    })) as { ok?: boolean; error?: string };
    if (!res.ok || !json.ok) {
      throw new Error(json.error ?? `HTTP ${res.status}`);
    }
  }

  return (
    <QueryBoundary
      query={caseQuery}
      skeleton={<CaseDetailSkeleton />}
      errorFallback={() => (
        <ErrorState
          title={ts.case_load_error ?? tCommon('error_loading')}
          action={
            <Button variant="secondary" size="sm" onClick={() => caseQuery.refetch()}>
              {tCommon('retry')}
            </Button>
          }
        />
      )}
    >
      {(data) => {
        const activeCase = data.case;
        if (!activeCase) return <InlineNotice tone="danger" title="Not found" />;

        const maxAmountCents = data.purchase?.totalCents ?? 100_000;
        const isClosed = activeCase.status === 'closed' || activeCase.status === 'resolved';
        const isClaimed = !!activeCase.assignedAgentId;
        const metadata = activeCase.metadata ?? {};
        const reassignCount =
          typeof metadata['reassign_count'] === 'number' ? metadata['reassign_count'] : 0;
        const interventions = (data.interventions ?? []) as unknown as AIInterventionView[];
        const aiRefundOffers = (data.offers ?? []).filter(
          (offer) =>
            offer.offeredBy === 'ai' &&
            (offer.outcome === 'refund_full' || offer.outcome === 'refund_partial'),
        );
        const aiRefundOffer =
          [...aiRefundOffers]
            .filter((offer) => {
              const execution = data.offerExecutions?.[offer.id];
              return (
                offer.status === 'pending' ||
                (execution?.status === 'failed' && execution.retryable)
              );
            })
            .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0] ??
          [...aiRefundOffers].sort(
            (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
          )[0];
        const aiOfferExecution = aiRefundOffer
          ? data.offerExecutions?.[aiRefundOffer.id]
          : undefined;
        const aiOfferCanExecute =
          aiRefundOffer?.status === 'pending' ||
          (aiOfferExecution?.status === 'failed' && aiOfferExecution.retryable);
        const latestIntervention =
          interventions.length > 0 ? interventions[interventions.length - 1] : null;
        const showAiRec =
          !aiRecDismissed &&
          latestIntervention?.decision === 'propose' &&
          latestIntervention.output != null;
        const aiRecToolName = latestIntervention?.toolName ?? '';
        const aiRecNeedsReturn =
          aiRecToolName === 'propose-return-approve' || aiRecToolName === 'propose-return-deny';
        const aiRecNeedsOffer = aiRecToolName === 'propose-refund';
        const aiRecExecuteDisabled =
          aiRecExecuting ||
          (aiRecNeedsOffer && !aiOfferCanExecute) ||
          (aiRecNeedsReturn && !activeCase.returnId);

        async function handleReturnApproveConfirm() {
          if (!activeCase.returnId) return;
          setActionError(null);
          setAiRecExecuting(true);
          try {
            await postReturnAction(`/api/admin/returns/${activeCase.returnId}/override`, {
              action: 'force_refund',
              reason: aiRecReason(latestIntervention?.output),
            });
            await caseQuery.refetch();
            setConfirmReturnApprove(false);
          } catch (err) {
            setActionError(err instanceof Error ? err.message : String(err));
          } finally {
            setAiRecExecuting(false);
          }
        }

        async function handleReturnDenyConfirm() {
          if (!activeCase.returnId) return;
          setActionError(null);
          setAiRecExecuting(true);
          try {
            await postReturnAction(`/api/admin/returns/${activeCase.returnId}/override`, {
              action: 'close',
              reason: aiRecReason(latestIntervention?.output),
            });
            await caseQuery.refetch();
            setConfirmReturnDeny(false);
          } catch (err) {
            setActionError(err instanceof Error ? err.message : String(err));
          } finally {
            setAiRecExecuting(false);
          }
        }

        async function handleAiResolveConfirm() {
          setActionError(null);
          setAiRecExecuting(true);
          try {
            await close.mutateAsync();
            await caseQuery.refetch();
            setConfirmAiResolve(false);
          } catch (err) {
            setActionError(err instanceof Error ? err.message : String(err));
          } finally {
            setAiRecExecuting(false);
          }
        }

        async function handleCloseConfirm() {
          setActionError(null);
          try {
            await close.mutateAsync();
            await caseQuery.refetch();
            setConfirmClose(false);
          } catch (err) {
            setActionError(err instanceof Error ? err.message : String(err));
          }
        }

        async function handleAiOfferConfirm() {
          if (!aiRefundOffer || !aiOfferCanExecute) return;
          setActionError(null);
          setAiOfferSuccess(false);
          setAiOfferExecuting(true);
          try {
            const response = await fetch(
              `/api/admin/support/cases/${caseId}/offers/${aiRefundOffer.id}/approve`,
              {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'x-csrf-token': getCsrfToken(),
                },
                body: JSON.stringify({}),
              },
            );
            const payload = (await response.json()) as {
              ok?: boolean;
              error?: string;
              data?: { inProgress?: boolean };
            };
            if (!response.ok || !payload.ok) {
              throw new Error(payload.error ?? `HTTP ${response.status}`);
            }
            setConfirmAiOffer(false);
            setAiOfferSuccess(!payload.data?.inProgress);
            await caseQuery.refetch();
          } catch (err) {
            captureCaught(err, {
              scope: 'AdminCaseDetail.handleAiOfferConfirm',
              severity: 'warning',
            });
            setActionError(tNav('ai_offer_approval_failed'));
            await caseQuery.refetch();
          } finally {
            setAiOfferExecuting(false);
          }
        }

        async function handleAiRecExecute(intervention: AIInterventionView) {
          setActionError(null);
          switch (intervention.toolName) {
            case 'propose-refund':
              if (!aiOfferCanExecute) return;
              setConfirmAiOffer(true);
              break;
            case 'propose-resolution':
              setConfirmAiResolve(true);
              break;
            case 'propose-return-approve':
              if (!activeCase.returnId) return;
              setConfirmReturnApprove(true);
              break;
            case 'propose-return-deny':
              if (!activeCase.returnId) return;
              setConfirmReturnDeny(true);
              break;
            case 'flag-vendor':
              console.warn(
                '[cs-agent] flag-vendor: no flag endpoint — routing to reassign-vendor dialog (closest available action)',
              );
              setReassignReason(aiRecReason(intervention.output));
              setConfirmReassign(true);
              break;
            default:
              break;
          }
        }

        return (
          <Grid cols={3} gap="6">
            <div className="md:col-span-2">
              <Stack gap="4">
                {actionError && <InlineNotice tone="danger" title={actionError} />}
                {aiOfferSuccess && <InlineNotice tone="success" title={tNav('ai_offer_success')} />}
                <SupportThread
                  messages={(data.messages ?? []) as never[]}
                  attachments={(data.attachments ?? []) as never[]}
                  viewerRole="admin"
                />
                {!isClosed && (
                  <div>
                    <div className="mb-2">
                      <Label className="mb-1 block text-xs">{ts.composer_visibility_label}</Label>
                      <Select
                        value={visibility}
                        onValueChange={(v) => setVisibility(v as 'public' | 'site_internal')}
                      >
                        <SelectTrigger className="w-48" aria-label={ts.composer_visibility_label}>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="public">{ts.visibility_public}</SelectItem>
                          <SelectItem value="site_internal">
                            {ts.visibility_site_internal}
                          </SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <SupportMessageComposer
                      ticketStatus={activeCase.status}
                      parentId={caseId}
                      parentType="case"
                      onSubmit={async (body) => {
                        await postMessage.mutateAsync({
                          text: body,
                          visibility,
                          attachmentIds: [],
                        });
                        await caseQuery.refetch();
                      }}
                    />
                  </div>
                )}
              </Stack>
            </div>

            <aside>
              <Stack gap="3">
                {!isClaimed && (
                  <Button
                    variant="primary"
                    size="sm"
                    aria-label={ts.action_claim}
                    title={ts.action_claim}
                    disabled={claim.isPending}
                    onClick={() => claim.mutate()}
                  >
                    {claim.isPending ? `${ts.action_claim}…` : ts.action_claim}
                  </Button>
                )}
                {!isClosed && (
                  <>
                    <Button variant="primary" size="sm" onClick={() => setRefundOpen(true)}>
                      {ts.action_issue_refund}
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => setConfirmDeny(true)}>
                      {ts.action_deny_refund}
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => setConfirmReplacement(true)}>
                      {ts.action_replacement}
                    </Button>
                    {reassignCount < 1 && (
                      <Button variant="ghost" size="sm" onClick={() => setConfirmReassign(true)}>
                        {ts.action_reassign_vendor}
                      </Button>
                    )}
                    <Button variant="ghost" size="sm" onClick={() => setConfirmClose(true)}>
                      {ts.action_close}
                    </Button>
                  </>
                )}

                {aiRefundOffer && (
                  <Stack gap="3">
                    <p className="text-sm font-semibold">{tNav('ai_offer_title')}</p>
                    <CaseOfferCard offer={aiRefundOffer} canDecide={false} />
                    {aiOfferExecution?.status === 'failed' && (
                      <InlineNotice tone="danger" title={tNav('ai_offer_failed')} />
                    )}
                    {aiOfferExecution?.status === 'processing' && (
                      <InlineNotice tone="info" title={tNav('ai_offer_processing')} />
                    )}
                    {aiOfferExecution?.status === 'completed' && (
                      <InlineNotice tone="success" title={tNav('ai_offer_success')} />
                    )}
                    {aiOfferCanExecute && (
                      <Button
                        variant="primary"
                        size="sm"
                        disabled={aiOfferExecuting}
                        aria-busy={aiOfferExecuting}
                        onClick={() => setConfirmAiOffer(true)}
                      >
                        {aiOfferExecuting
                          ? `${tNav(
                              aiOfferExecution?.status === 'failed'
                                ? 'ai_offer_retry'
                                : 'ai_offer_approve',
                            )}…`
                          : tNav(
                              aiOfferExecution?.status === 'failed'
                                ? 'ai_offer_retry'
                                : 'ai_offer_approve',
                            )}
                      </Button>
                    )}
                  </Stack>
                )}

                {showAiRec && latestIntervention && (
                  <div className="border-border-default rounded-lg border p-4">
                    <Stack gap="3">
                      <Row gap="2" align="center">
                        <Badge tone="info" size="sm">
                          {tNav('ai_rec_title')}
                        </Badge>
                        <Badge tone="neutral" size="sm">
                          {aiDecisionLabel(latestIntervention.decision, (k) => tNav(k as never))}
                        </Badge>
                      </Row>
                      <div>
                        <p className="text-text-muted mb-1 text-xs font-medium">
                          {tNav('ai_rec_reasoning')}
                        </p>
                        <p className="text-sm">{latestIntervention.output}</p>
                      </div>
                      {latestIntervention.confidence != null && (
                        <div>
                          <p className="text-text-muted mb-1 text-xs font-medium">
                            {tNav('ai_rec_confidence')}
                          </p>
                          <ConfidenceBar value={latestIntervention.confidence} />
                        </div>
                      )}
                      <Row gap="2">
                        <Button
                          variant="primary"
                          size="sm"
                          disabled={aiRecExecuteDisabled}
                          title={
                            aiRecNeedsOffer && !aiOfferCanExecute
                              ? tNav('ai_offer_missing')
                              : aiRecNeedsReturn && !activeCase.returnId
                                ? tNav('ai_rec_no_return')
                                : undefined
                          }
                          onClick={() => void handleAiRecExecute(latestIntervention)}
                          aria-busy={aiRecExecuting}
                        >
                          {aiRecExecuting
                            ? `${aiRecExecuteLabel(
                                latestIntervention.toolName,
                                tNav as (key: string) => string,
                              )}...`
                            : aiRecExecuteLabel(
                                latestIntervention.toolName,
                                tNav as (key: string) => string,
                              )}
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          title={tNav('ai_rec_dismiss')}
                          onClick={() => setAiRecDismissed(true)}
                        >
                          {tNav('ai_rec_dismiss')}
                        </Button>
                      </Row>
                    </Stack>
                  </div>
                )}

                <ContextPanel
                  parentType="case"
                  parentId={caseId}
                  purchaseId={activeCase.purchaseId}
                  customerId={activeCase.customerId}
                  vendorId={activeCase.vendorId}
                  attachments={(data.attachments ?? []) as never[]}
                  interventions={(data.interventions ?? []) as never[]}
                  transitions={(data.transitions ?? []) as never[]}
                />
              </Stack>
            </aside>

            <AlertDialog open={confirmAiOffer} onOpenChange={setConfirmAiOffer}>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>{tNav('ai_offer_confirm_title')}</AlertDialogTitle>
                  <AlertDialogDescription>{tNav('ai_offer_confirm_body')}</AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel disabled={aiOfferExecuting}>
                    {tCommon('cancel')}
                  </AlertDialogCancel>
                  <AlertDialogAction
                    disabled={aiOfferExecuting}
                    aria-busy={aiOfferExecuting}
                    onClick={(event) => {
                      event.preventDefault();
                      void handleAiOfferConfirm();
                    }}
                  >
                    {aiOfferExecuting
                      ? `${tNav(
                          aiOfferExecution?.status === 'failed'
                            ? 'ai_offer_retry'
                            : 'ai_offer_approve',
                        )}…`
                      : tNav(
                          aiOfferExecution?.status === 'failed'
                            ? 'ai_offer_retry'
                            : 'ai_offer_approve',
                        )}
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>

            <AdminRefundDialog
              open={refundOpen}
              onOpenChange={setRefundOpen}
              caseId={caseId}
              purchaseId={activeCase.purchaseId ?? ''}
              maxAmountCents={maxAmountCents}
              onSuccess={async () => {
                await caseQuery.refetch();
              }}
            />

            <AlertDialog open={confirmDeny} onOpenChange={setConfirmDeny}>
              <AlertDialogContent>
                <AlertDialogTitle>{ts.action_deny_refund}</AlertDialogTitle>
                <AlertDialogDescription>{ts.confirm_deny_refund_body}</AlertDialogDescription>
                <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                <AlertDialogAction
                  onClick={() => handleDecide({ outcome: 'deny', reason: ts.reason_admin_denied })}
                >
                  {ts.action_deny_refund}
                </AlertDialogAction>
              </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmReplacement} onOpenChange={setConfirmReplacement}>
              <AlertDialogContent>
                <AlertDialogTitle>{ts.action_replacement}</AlertDialogTitle>
                <AlertDialogDescription>{ts.confirm_replacement_body}</AlertDialogDescription>
                <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                <AlertDialogAction
                  onClick={() =>
                    handleDecide({ outcome: 'replacement', reason: ts.reason_admin_replacement })
                  }
                >
                  {ts.action_replacement}
                </AlertDialogAction>
              </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmClose} onOpenChange={setConfirmClose}>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>{ts.action_close}</AlertDialogTitle>
                  <AlertDialogDescription>{ts.confirm_close_case_body}</AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                  <AlertDialogAction onClick={handleCloseConfirm}>
                    {ts.action_close}
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmReturnApprove} onOpenChange={setConfirmReturnApprove}>
              <AlertDialogContent>
                <AlertDialogTitle>{tNav('ai_rec_approve_return')}</AlertDialogTitle>
                <AlertDialogDescription>
                  {data.purchase?.totalCents != null
                    ? tNav('ai_rec_confirm_return_approve').replace(
                        '{amount}',
                        formatAgorotShekels(maxAmountCents),
                      )
                    : tNav('ai_rec_confirm_return_approve_noamount')}
                </AlertDialogDescription>
                <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                <AlertDialogAction onClick={() => void handleReturnApproveConfirm()}>
                  {tNav('ai_rec_approve_return')}
                </AlertDialogAction>
              </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmReturnDeny} onOpenChange={setConfirmReturnDeny}>
              <AlertDialogContent>
                <AlertDialogTitle>{tNav('ai_rec_deny_return')}</AlertDialogTitle>
                <AlertDialogDescription>
                  {tNav('ai_rec_confirm_return_deny')}
                </AlertDialogDescription>
                <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                <AlertDialogAction onClick={() => void handleReturnDenyConfirm()}>
                  {tNav('ai_rec_deny_return')}
                </AlertDialogAction>
              </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmAiResolve} onOpenChange={setConfirmAiResolve}>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>{ts.action_close}</AlertDialogTitle>
                  <AlertDialogDescription>{tNav('ai_rec_confirm_resolve')}</AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={() => void handleAiResolveConfirm()}
                    disabled={aiRecExecuting}
                  >
                    {ts.action_close}
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>

            <AlertDialog open={confirmReassign} onOpenChange={setConfirmReassign}>
              <AlertDialogContent>
                <AlertDialogTitle>{ts.action_reassign_vendor}</AlertDialogTitle>
                <div className="mt-3">
                  <Label htmlFor="reassign-reason">{ts.field_transition_reason}</Label>
                  <Textarea
                    id="reassign-reason"
                    value={reassignReason}
                    onChange={(e) => setReassignReason(e.target.value)}
                    rows={3}
                    className="mt-1"
                  />
                </div>
                <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                <AlertDialogAction
                  onClick={() =>
                    handleDecide({ outcome: 'reassign_vendor', reason: reassignReason })
                  }
                >
                  {ts.action_reassign_vendor}
                </AlertDialogAction>
              </AlertDialogContent>
            </AlertDialog>
          </Grid>
        );
      }}
    </QueryBoundary>
  );
}

export function AdminCaseDetail({ caseId }: { caseId: string }) {
  return (
    <HydratedIsland>
      <CaseDetailInner caseId={caseId} />
    </HydratedIsland>
  );
}
