/**
 * VendorCaseDetail — full case view for the vendor.
 * Shows customer ask, current status, respond form (if vendor_review state),
 * message thread.
 */

'use client';

import { useQuery } from '@tanstack/react-query';
import { useT, useLocale } from '@/lib/i18n/react';
import { formatDateTime } from '@/lib/format';
import type { StringBundle } from '@/lib/i18n/types';
import { CaseDetailSkeleton, SkeletonGuard } from '@/components/ui/feedback/Skeleton';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { Button } from '@/components/ui/primitives/Button';
import { CaseStatusTimeline } from '@/components/ui/domain/support/CaseStatusTimeline';
import { CaseOfferCard } from '@/components/ui/domain/support/CaseOfferCard';
import { VendorRespondCard } from '@/components/ui/domain/support/VendorRespondCard';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import type {
  CaseSummaryView,
  CaseOfferView,
  SupportMessageView,
  StateTransitionView,
} from '@/server/support/types';
import { usePostOffer } from './useCaseMutations';
import { ErrorBoundary } from '@/components/ui/feedback/ErrorBoundary';
import { HydratedIsland } from '@/components/HydratedIsland';
import { qk } from '@/lib/query/keys';

interface CaseDetailData {
  case: CaseSummaryView;
  offers: CaseOfferView[];
  messages: SupportMessageView[];
  transitions: StateTransitionView[];
}

async function fetchCase(caseId: string): Promise<CaseDetailData> {
  const res = await fetch(`/api/cases/${caseId}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json() as Promise<CaseDetailData>;
}

export interface VendorCaseDetailProps {
  caseId: string;
}

export function VendorCaseDetail(props: VendorCaseDetailProps) {
  return (
    <HydratedIsland>
      <VendorCaseDetailInner {...props} />
    </HydratedIsland>
  );
}

function VendorCaseDetailInner({ caseId }: VendorCaseDetailProps) {
  const t = useT('cases');
  const tCommon = useT('common');
  const { locale } = useLocale();
  const tDetail = t('detail') as unknown as StringBundle['cases']['detail'];
  const tVendor = t('vendor') as unknown as StringBundle['cases']['vendor'];
  const tCategories = t('categories') as unknown as StringBundle['cases']['categories'];
  const tStatus = t('status') as unknown as StringBundle['cases']['status'];

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: qk.case(caseId),
    queryFn: () => fetchCase(caseId),
  });

  const offerMut = usePostOffer();

  if (isLoading && !data)
    return (
      <div aria-busy="true" role="status">
        <SkeletonGuard delay={0}>
          <CaseDetailSkeleton />
        </SkeletonGuard>
      </div>
    );
  if (isError) {
    return (
      <ErrorState
        title={tCommon('error_loading')}
        action={
          <Button variant="secondary" size="sm" onClick={() => refetch()}>
            {tCommon('retry')}
          </Button>
        }
      />
    );
  }
  if (!data) return null;

  const { case: c, offers, messages, transitions } = data;

  const canOffer = c.status === 'vendor_review' || c.status === 'vendor_offered';
  const autoExecuted = offers.some((o) => o.status === 'auto_executed');
  const isResolved = c.status === 'resolved' || c.status === 'closed';

  return (
    <ErrorBoundary>
      <article className="space-y-6">
        <header>
          <h1 className="text-foreground text-xl font-bold">
            {tCategories[c.category as keyof StringBundle['cases']['categories']] ?? c.category}
          </h1>
          <p className="text-muted text-sm">
            {tStatus[c.status as keyof StringBundle['cases']['status']] ?? c.status}
          </p>
        </header>

        {autoExecuted && <InlineNotice tone="success" title={tVendor.auto_executed} />}
        {isResolved && !autoExecuted && (
          <InlineNotice tone="success" title={tDetail.resolved_banner} />
        )}

        {/* Previous offers */}
        {offers.length > 0 && (
          <section aria-label={tVendor.offer_sent} className="space-y-3">
            {offers.map((offer) => (
              <CaseOfferCard key={offer.id} offer={offer} canDecide={false} />
            ))}
          </section>
        )}

        {/* Respond form */}
        {canOffer && (
          <section aria-label={tVendor.respond_cta}>
            <h2 className="text-foreground mb-3 text-sm font-semibold">{tVendor.respond_cta}</h2>
            <VendorRespondCard
              submitting={offerMut.isPending}
              onSubmit={async (values) => {
                await offerMut.mutateAsync({
                  caseId,
                  outcome: values.outcome,
                  amountCents: values.amountCents,
                  reason: values.reason,
                });
              }}
            />
            {offerMut.isSuccess && offerMut.data.autoExecuted && (
              <InlineNotice tone="success" title={tVendor.auto_executed} />
            )}
            {offerMut.isSuccess && !offerMut.data.autoExecuted && (
              <InlineNotice tone="info" title={tVendor.offer_sent} />
            )}
          </section>
        )}

        {/* Timeline */}
        <CaseStatusTimeline transitions={transitions} />

        {/* Messages */}
        {messages.length > 0 && (
          <section aria-label={tDetail.thread_title} className="space-y-2">
            <h2 className="text-muted text-sm font-semibold">{tDetail.thread_title}</h2>
            <ul className="space-y-2">
              {messages.map((m) => (
                <li key={m.id} className="border-border rounded-lg border p-3 text-sm">
                  <p className="text-foreground">{m.body}</p>
                  <time className="text-muted text-xs">{formatDateTime(m.createdAt, locale)}</time>
                </li>
              ))}
            </ul>
          </section>
        )}
      </article>
    </ErrorBoundary>
  );
}
