'use client';

/**
 * ContextPanel — right-hand info panel for admin ticket/case detail.
 * Shows ticket stats, transaction summary, vendor info, user history,
 * vendor history, attachments, AI reasoning, and state timeline.
 */

import { useT } from '@/lib/i18n/react';
import { fmtDuration, formatDate } from '@/lib/format';
import { useLocale } from '@/lib/i18n/react';
import { AttachmentGallery } from '@/components/ui/domain/support/AttachmentGallery';
import { AIReasoningPanel } from '@/components/ui/domain/support/AIReasoningPanel';
import { Skeleton } from '@/components/ui/feedback/Skeleton';
import { Stack } from '@/components/ui/layout/Stack';
import { StateTransitionsTimeline } from './StateTransitionsTimeline';
import type {
  AIInterventionView,
  StateTransitionView,
  SupportAttachmentView,
} from '@/server/support/types';

export interface ContextPanelProps {
  parentType: 'ticket' | 'case';
  parentId: string;
  isLoading?: boolean;
  purchaseId?: string | null;
  customerId?: string | null;
  vendorId?: string | null;
  vendorName?: string | null;
  vendorBusinessName?: string | null;
  attachments?: SupportAttachmentView[];
  interventions?: AIInterventionView[];
  transitions?: StateTransitionView[];
  userTicketCount?: number;
  userCaseCount?: number;
  userPurchaseCount?: number;
  vendorOpenCaseCount?: number;
  vendorActiveDealCount?: number;
  vendorMissPct?: number;
  ticketOpenedAt?: string | null;
  firstResponseMs?: number | null;
  avgFirstResponseMs?: number | null;
  messageCount?: number;
}

function SectionHeading({ id, children }: { id: string; children: React.ReactNode }) {
  return (
    <h3 id={id} className="text-text-muted mb-2 text-xs font-semibold tracking-wide uppercase">
      {children}
    </h3>
  );
}

function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between gap-2 py-0.5">
      <dt className="text-text-muted text-xs">{label}</dt>
      <dd className="text-text-primary text-xs font-medium">{value}</dd>
    </div>
  );
}

export function ContextPanel({
  parentType,
  isLoading,
  purchaseId,
  customerId,
  vendorId,
  vendorName,
  vendorBusinessName,
  attachments = [],
  interventions = [],
  transitions = [],
  userTicketCount,
  userCaseCount,
  userPurchaseCount,
  vendorOpenCaseCount,
  vendorActiveDealCount,
  vendorMissPct,
  ticketOpenedAt,
  firstResponseMs,
  avgFirstResponseMs,
  messageCount,
}: ContextPanelProps) {
  const t = useT('admin');
  const ts = t('support') as unknown as Record<string, string>;
  const tNav = useT('admin_support');
  const { locale } = useLocale();

  if (isLoading) {
    return (
      <Stack gap="4">
        <Skeleton className="h-24 w-full" />
        <Skeleton className="h-20 w-full" />
        <Skeleton className="h-20 w-full" />
      </Stack>
    );
  }

  const deltaMs =
    firstResponseMs != null && avgFirstResponseMs != null
      ? firstResponseMs - avgFirstResponseMs
      : null;

  return (
    <Stack gap="5" className="text-sm">
      {/* Ticket stats */}
      {(ticketOpenedAt != null || firstResponseMs != null || messageCount != null) && (
        <section aria-labelledby="ctx-ticket-stats">
          <SectionHeading id="ctx-ticket-stats">{ts.ctx_ticket_stats}</SectionHeading>
          <dl>
            {ticketOpenedAt != null && (
              <InfoRow
                label={ts.ctx_opened_at ?? ''}
                value={ticketOpenedAt ? formatDate(ticketOpenedAt, locale) : '—'}
              />
            )}
            {messageCount != null && <InfoRow label={ts.ctx_messages ?? ''} value={messageCount} />}
            {firstResponseMs != null && (
              <InfoRow label={ts.ctx_first_response ?? ''} value={fmtDuration(firstResponseMs)} />
            )}
            {avgFirstResponseMs != null && (
              <InfoRow label={ts.ctx_avg_response ?? ''} value={fmtDuration(avgFirstResponseMs)} />
            )}
            {deltaMs != null && (
              <InfoRow
                label={ts.ctx_response_vs_avg ?? ''}
                value={
                  <span className={deltaMs <= 0 ? 'text-feedback-success' : 'text-feedback-danger'}>
                    {deltaMs <= 0 ? '-' : '+'}
                    {fmtDuration(Math.abs(deltaMs))}
                  </span>
                }
              />
            )}
          </dl>
        </section>
      )}

      {/* Transaction summary */}
      {purchaseId && (
        <section aria-labelledby="ctx-transaction">
          <SectionHeading id="ctx-transaction">{ts.ctx_transaction}</SectionHeading>
          <dl>
            <InfoRow
              label={ts.ctx_purchase_id ?? ''}
              value={<span className="font-mono text-xs">{purchaseId.slice(0, 8)}…</span>}
            />
          </dl>
        </section>
      )}

      {/* Vendor info */}
      {vendorId != null && (vendorName != null || vendorBusinessName != null) && (
        <section aria-labelledby="ctx-vendor-info">
          <SectionHeading id="ctx-vendor-info">{ts.ctx_vendor_info}</SectionHeading>
          <dl>
            {(vendorName ?? vendorBusinessName) != null && (
              <InfoRow
                label={ts.ctx_vendor_name ?? ''}
                value={
                  <a
                    href={`/admin/vendors/${vendorId}`}
                    className="text-brand-primary-600 hover:underline"
                  >
                    {vendorName ?? vendorBusinessName}
                  </a>
                }
              />
            )}
            {vendorActiveDealCount != null && (
              <InfoRow label={ts.ctx_vendor_active_deals ?? ''} value={vendorActiveDealCount} />
            )}
          </dl>
        </section>
      )}

      {/* User history */}
      {customerId != null && (userTicketCount != null || userCaseCount != null) && (
        <section aria-labelledby="ctx-user">
          <SectionHeading id="ctx-user">{ts.ctx_user_history}</SectionHeading>
          <dl>
            {userPurchaseCount != null && (
              <InfoRow label={ts.ctx_purchases ?? ''} value={userPurchaseCount} />
            )}
            {userTicketCount != null && (
              <InfoRow label={ts.ctx_open_tickets ?? ''} value={userTicketCount} />
            )}
            {userCaseCount != null && <InfoRow label={ts.ctx_cases ?? ''} value={userCaseCount} />}
          </dl>
        </section>
      )}

      {/* Vendor history */}
      {vendorId != null && (vendorOpenCaseCount != null || vendorMissPct != null) && (
        <section aria-labelledby="ctx-vendor">
          <SectionHeading id="ctx-vendor">{ts.ctx_vendor_history}</SectionHeading>
          <dl>
            {vendorOpenCaseCount != null && (
              <InfoRow label={ts.ctx_open_cases ?? ''} value={vendorOpenCaseCount} />
            )}
            {vendorMissPct != null && (
              <InfoRow label={ts.ctx_miss_rate ?? ''} value={`${vendorMissPct}%`} />
            )}
          </dl>
        </section>
      )}

      {/* Attachments */}
      {attachments.length > 0 && (
        <section aria-labelledby="ctx-attachments">
          <SectionHeading id="ctx-attachments">{ts.ctx_attachments}</SectionHeading>
          <AttachmentGallery attachments={attachments} viewerRole="admin" />
        </section>
      )}

      {/* Knowledge context */}
      {interventions.length > 0 && interventions[interventions.length - 1]?.input != null && (
        <section aria-labelledby="ctx-knowledge">
          <details className="border-border-default rounded-lg border">
            <summary className="text-text-primary cursor-pointer px-3 py-2 text-sm font-medium">
              {tNav('ctx_knowledge')}
            </summary>
            <pre className="bg-surface-raised max-h-48 overflow-auto rounded p-2 text-xs whitespace-pre-wrap">
              {interventions[interventions.length - 1]?.input}
            </pre>
          </details>
        </section>
      )}

      {/* AI reasoning */}
      {interventions.length > 0 && (
        <section aria-labelledby="ctx-ai">
          <SectionHeading id="ctx-ai">{ts.ctx_ai_reasoning}</SectionHeading>
          <AIReasoningPanel interventions={interventions} />
        </section>
      )}

      {/* State timeline */}
      {transitions.length > 0 && (
        <section aria-labelledby="ctx-timeline">
          <SectionHeading id="ctx-timeline">{ts.ctx_timeline}</SectionHeading>
          <StateTransitionsTimeline parentType={parentType} transitions={transitions} />
        </section>
      )}
    </Stack>
  );
}
