// src/features/admin-purchase-detail/PurchaseDetail.tsx
// Admin: purchase drill-down page - overview layout with header, parties,
// deal snapshot, payment info, timeline, and review (if any).

'use client';

import { useRef, useState } from 'react';
import { getCsrfToken } from '@/lib/csrf';
import { useT, useLocale, LocaleProvider } from '@/lib/i18n/react';
import type { Locale } from '@/lib/i18n/index';
import { Button } from '@/components/ui/primitives/Button';
import { Stack } from '@/components/ui/layout/Stack';
import { Pill } from '@/components/ui/primitives/Pill';
import {
  AlertDialog,
  AlertDialogTrigger,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogAction,
  AlertDialogCancel,
} from '@/components/ui/overlays/AlertDialog';
import { captureCaught } from '@/lib/observability';
import { formatDate, formatDateTime } from '@/lib/format';
import { enumLabel } from '@/lib/enums/enum-labels';
import {
  getActionIdempotencyKey,
  resetActionIdempotencyKey,
} from '@/lib/stable-action-idempotency';

// ─── Types ────────────────────────────────────────────────────────────────────

export interface PurchaseDetailPurchaseData {
  id: string;
  userId: string | null;
  dealId: string;
  vendorId: string | null;
  quantity: number;
  amountPaid: string;
  commissionAmount: string;
  vendorAmount: string;
  paymentStatus: string;
  redemptionStatus: string | null;
  providerPaymentId: string | null;
  qrPngUrl: string | null;
  createdAt: string;
  redeemedAt: string | null;
  cancelledAt: string | null;
  expiresAt: string | null;
  isGuest: boolean;
}

export interface PurchaseDetailCustomerData {
  id: string;
  displayName: string | null;
  accountState: string;
  isAdmin: boolean;
  createdAt: string;
}

export interface PurchaseDetailVendorData {
  id: string;
  displayName: string;
  businessName: string;
  accountState: string;
}

export interface PurchaseDetailDealData {
  id: string;
  title: string;
  dealType: string;
  originalPrice: string;
  discountPercent: number;
  discountedPrice: string;
  windowStart: string | null;
  windowEnd: string | null;
  pickupAddress: string;
}

export interface PurchaseDetailReviewData {
  id: string;
  rating: number | null;
  body: string;
  reviewType: string;
  isVisible: boolean;
  createdAt: string;
}

export interface PurchaseDetailProps {
  purchase: PurchaseDetailPurchaseData;
  customer: PurchaseDetailCustomerData | null;
  vendor: PurchaseDetailVendorData;
  deal: PurchaseDetailDealData;
  review: PurchaseDetailReviewData | null;
  initialLocale: Locale;
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="border-border-subtle grid grid-cols-2 gap-2 border-b py-2 last:border-0">
      <dt className="text-text-secondary text-sm">{label}</dt>
      <dd className="text-text-primary text-sm font-medium">{value ?? '—'}</dd>
    </div>
  );
}

function SectionTitle({ children }: { children: React.ReactNode }) {
  return <h2 className="mb-3 text-2xl font-[var(--font-weight-extrabold)]">{children}</h2>;
}

function Card({ children }: { children: React.ReactNode }) {
  return <div className="bg-surface-default rounded-2xl p-4 shadow-md">{children}</div>;
}

// ─── Timeline Step ────────────────────────────────────────────────────────────

function TimelineStep({
  label,
  date,
  done,
  locale,
}: {
  label: string;
  date: string | null;
  done: boolean;
  locale: Locale;
}) {
  return (
    <div className="flex items-start gap-3">
      <div
        className={`mt-1 h-3 w-3 shrink-0 rounded-full border-2 ${
          done ? 'border-success-600 bg-success-600' : 'border-border-strong bg-surface-base'
        }`}
        aria-hidden="true"
      />
      <div>
        <p className={`text-sm font-medium ${done ? 'text-text-primary' : 'text-text-secondary'}`}>
          {label}
        </p>
        {date && <p className="text-text-secondary text-xs">{formatDateTime(date, locale)}</p>}
      </div>
    </div>
  );
}

// ─── Component ────────────────────────────────────────────────────────────────

export function PurchaseDetail({ initialLocale, ...props }: PurchaseDetailProps) {
  return (
    <LocaleProvider locale={initialLocale}>
      <PurchaseDetailInner {...props} />
    </LocaleProvider>
  );
}

function PurchaseDetailInner({
  purchase: initialPurchase,
  customer,
  vendor,
  deal,
  review,
}: Omit<PurchaseDetailProps, 'initialLocale'>) {
  const t = useT('admin_purchase_detail');
  const tCommon = useT('common');
  const { locale } = useLocale();

  const [purchase, setPurchase] = useState(initialPurchase);
  const [loading, setLoading] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const refundEventId = useRef<string | null>(null);

  // ── Payment status helpers ────────────────────────────────────────────────

  const paymentToneMap: Record<string, 'success' | 'warning' | 'danger' | 'neutral' | 'info'> = {
    COMPLETED: 'success',
    PENDING: 'warning',
    REFUND_REQUESTED: 'info',
    REFUNDED: 'danger',
    PARTIAL_REFUND: 'danger',
  };

  const redemptionToneMap: Record<string, 'success' | 'warning' | 'danger' | 'neutral' | 'info'> = {
    REDEEMED: 'success',
    UNREDEEMED: 'info',
    CANCELLED: 'danger',
    EXPIRED: 'neutral',
  };

  // ── Refund action ─────────────────────────────────────────────────────────

  async function handleRefund() {
    setLoading('refund');
    setError(null);
    setSuccessMsg(null);
    try {
      const res = await fetch(`/api/admin/purchases/${purchase.id}/refund`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-csrf-token': getCsrfToken(),
          'Idempotency-Key': getActionIdempotencyKey(refundEventId),
        },
        body: JSON.stringify({}),
      });
      const json = (await res.json().catch((err) => {
        captureCaught(err, {
          scope: 'features.admin-purchase-detail.PurchaseDetail',
          severity: 'info',
        });
        return {};
      })) as {
        ok?: boolean;
        data?: { status?: string; refundedAgorot?: number };
        error?: string;
      };
      if (!res.ok || json.ok === false) {
        throw new Error(json.error || `HTTP ${res.status}`);
      }
      const refundedAgorot = json.data?.refundedAgorot ?? 0;
      const paidAgorot = Math.round(parseFloat(purchase.amountPaid) * 100);
      const nextStatus =
        json.data?.status ??
        (refundedAgorot > 0 && refundedAgorot < paidAgorot ? 'PARTIAL_REFUND' : 'REFUNDED');
      setPurchase((prev) => ({ ...prev, paymentStatus: nextStatus }));
      setSuccessMsg(t('refund_success'));
      resetActionIdempotencyKey(refundEventId);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(null);
    }
  }

  // ── Resend receipt action ─────────────────────────────────────────────────

  async function handleResendReceipt() {
    setLoading('resend');
    setError(null);
    setSuccessMsg(null);
    try {
      const res = await fetch(`/api/admin/purchases/${purchase.id}/resend-receipt`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-csrf-token': getCsrfToken(),
        },
        body: JSON.stringify({}),
      });
      if (!res.ok) {
        const json = (await res.json().catch((err) => {
          captureCaught(err, {
            scope: 'features.admin-purchase-detail.PurchaseDetail',
            severity: 'info',
          });
          return {};
        })) as Record<string, unknown>;
        throw new Error((json.error as string) || `HTTP ${res.status}`);
      }
      setSuccessMsg(t('resend_receipt_success'));
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(null);
    }
  }

  // ── Timeline steps ────────────────────────────────────────────────────────

  const timelineSteps = [
    {
      key: 'created',
      label: t('timeline_created'),
      date: purchase.createdAt,
      done: true,
    },
    {
      key: 'paid',
      label: t('timeline_paid'),
      date:
        purchase.paymentStatus === 'COMPLETED' ||
        purchase.paymentStatus === 'REFUNDED' ||
        purchase.paymentStatus === 'PARTIAL_REFUND' ||
        purchase.paymentStatus === 'REFUND_REQUESTED'
          ? purchase.createdAt
          : null,
      done:
        purchase.paymentStatus === 'COMPLETED' ||
        purchase.paymentStatus === 'REFUNDED' ||
        purchase.paymentStatus === 'PARTIAL_REFUND' ||
        purchase.paymentStatus === 'REFUND_REQUESTED',
    },
    {
      key: 'terminal',
      label:
        purchase.redemptionStatus === 'REDEEMED'
          ? t('timeline_redeemed')
          : purchase.redemptionStatus === 'CANCELLED'
            ? t('timeline_cancelled')
            : purchase.redemptionStatus === 'EXPIRED'
              ? t('timeline_expired')
              : t('timeline_pending_redemption'),
      date: purchase.redeemedAt ?? purchase.cancelledAt ?? null,
      done:
        purchase.redemptionStatus === 'REDEEMED' ||
        purchase.redemptionStatus === 'CANCELLED' ||
        purchase.redemptionStatus === 'EXPIRED',
    },
  ];

  // ─────────────────────────────────────────────────────────────────────────

  return (
    <div className="mx-auto max-w-5xl">
      {/* ── Status pills ───────────────────────────────────────────────────── */}
      <div className="mb-6 flex flex-wrap items-center gap-3">
        <Pill tone={paymentToneMap[purchase.paymentStatus] ?? 'neutral'} size="sm">
          {`${t('payment_status_prefix')}: ${enumLabel('payment_status', purchase.paymentStatus, locale, 'admin')}`}
        </Pill>
        <Pill tone={redemptionToneMap[purchase.redemptionStatus ?? ''] ?? 'neutral'} size="sm">
          {`${t('redemption_status_prefix')}: ${enumLabel('purchase_status', purchase.redemptionStatus ?? '', locale, 'admin')}`}
        </Pill>
      </div>

      {/* ── Feedback ───────────────────────────────────────────────────────── */}
      {error && (
        <p role="alert" className="text-danger-600 mb-4 text-sm">
          {error}
        </p>
      )}
      {successMsg && (
        <p role="status" className="text-success-700 mb-4 text-sm">
          {successMsg}
        </p>
      )}

      <div className="grid gap-6 lg:grid-cols-3">
        {/* ── Main content (2 cols) ─────────────────────────────────────── */}
        <div className="space-y-6 lg:col-span-2">
          {/* Parties */}
          <Card>
            <SectionTitle>{t('section_parties')}</SectionTitle>
            <dl>
              <InfoRow
                label={t('field_customer')}
                value={
                  purchase.isGuest ? (
                    <span className="text-text-secondary italic">{t('guest_label')}</span>
                  ) : customer ? (
                    <a
                      href={`/admin/users/${customer.id}`}
                      className="text-brand-primary-600 hover:text-brand-primary-800 underline-offset-2 hover:underline"
                      data-user-displayname
                    >
                      {customer.displayName || t('customer_unnamed')}
                    </a>
                  ) : (
                    '—'
                  )
                }
              />
              <InfoRow
                label={t('field_vendor')}
                value={
                  <a
                    href={`/admin/vendors/${vendor.id}`}
                    className="text-brand-primary-600 hover:text-brand-primary-800 underline-offset-2 hover:underline"
                    data-user-displayname
                  >
                    {vendor.displayName}
                  </a>
                }
              />
            </dl>
          </Card>

          {/* Deal snapshot */}
          <Card>
            <SectionTitle>{t('section_deal')}</SectionTitle>
            <dl>
              <InfoRow
                label={t('field_deal_title')}
                value={<span data-user-displayname>{deal.title}</span>}
              />
              <InfoRow
                label={t('field_deal_type')}
                value={(t as (k: string) => string)(`deal_type_${deal.dealType}`) || deal.dealType}
              />
              <InfoRow
                label={t('field_deal_original_price')}
                value={`${t('currency_symbol')}${Number(deal.originalPrice).toFixed(2)}`}
              />
              <InfoRow label={t('field_deal_discount')} value={`${deal.discountPercent ?? 0}%`} />
              <InfoRow
                label={t('field_deal_discounted_price')}
                value={`${t('currency_symbol')}${Number(deal.discountedPrice).toFixed(2)}`}
              />
              {deal.windowStart && (
                <InfoRow
                  label={t('field_deal_window_start')}
                  value={formatDateTime(deal.windowStart, locale)}
                />
              )}
              {deal.windowEnd && (
                <InfoRow
                  label={t('field_deal_window_end')}
                  value={formatDateTime(deal.windowEnd, locale)}
                />
              )}
              {deal.pickupAddress && (
                <InfoRow label={t('field_deal_pickup_address')} value={deal.pickupAddress} />
              )}
            </dl>
          </Card>

          {/* Payment info */}
          <Card>
            <SectionTitle>{t('section_payment')}</SectionTitle>
            <dl>
              <InfoRow
                label={t('field_amount_paid')}
                value={`${t('currency_symbol')}${Number(purchase.amountPaid).toFixed(2)}`}
              />
              <InfoRow
                label={t('field_commission_amount')}
                value={`${t('currency_symbol')}${Number(purchase.commissionAmount).toFixed(2)}`}
              />
              <InfoRow
                label={t('field_vendor_amount')}
                value={`${t('currency_symbol')}${Number(purchase.vendorAmount).toFixed(2)}`}
              />
              <InfoRow
                label={t('field_provider_payment_id')}
                value={purchase.providerPaymentId ?? '—'}
              />
              <InfoRow label={t('field_quantity')} value={String(purchase.quantity)} />
            </dl>
          </Card>

          {/* Review */}
          {review && (
            <Card>
              <SectionTitle>{t('section_review')}</SectionTitle>
              <dl>
                {review.rating !== null && (
                  <InfoRow label={t('field_review_rating')} value={`${review.rating} / 5`} />
                )}
                <InfoRow
                  label={t('field_review_type')}
                  value={
                    (t as (k: string) => string)(`review_type_${review.reviewType}`) ||
                    enumLabel('review_type', review.reviewType, locale)
                  }
                />
                <InfoRow
                  label={t('field_review_visible')}
                  value={
                    review.isVisible ? (
                      <Pill tone="success" size="sm">
                        {t('review_visible_yes')}
                      </Pill>
                    ) : (
                      <Pill tone="neutral" size="sm">
                        {t('review_visible_no')}
                      </Pill>
                    )
                  }
                />
                <InfoRow
                  label={t('field_review_date')}
                  value={formatDate(review.createdAt, locale)}
                />
                <InfoRow label={t('field_review_body')} value={review.body} />
              </dl>
            </Card>
          )}
        </div>

        {/* ── Sidebar (1 col) ───────────────────────────────────────────── */}
        <div className="space-y-6">
          {/* Timeline */}
          <Card>
            <SectionTitle>{t('section_timeline')}</SectionTitle>
            <div className="flex flex-col gap-4">
              {timelineSteps.map((step) => (
                <TimelineStep
                  key={step.key}
                  label={step.label}
                  date={step.date}
                  done={step.done}
                  locale={locale}
                />
              ))}
            </div>
          </Card>

          {/* Actions */}
          <Card>
            <SectionTitle>{t('section_actions')}</SectionTitle>
            <Stack gap="3">
              {purchase.paymentStatus !== 'COMPLETED' && (
                <p className="text-text-secondary text-sm">
                  {t('refund_unavailable_hint').replace(
                    '{{status}}',
                    `${t('payment_status_prefix')}: ${enumLabel('payment_status', purchase.paymentStatus, locale, 'admin')}`,
                  )}
                </p>
              )}

              {/* Refund — only available when status is COMPLETED */}
              {purchase.paymentStatus === 'COMPLETED' && (
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="danger" size="sm" disabled={loading === 'refund'}>
                      {loading === 'refund' ? tCommon('loading') : t('action_refund')}
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>{t('refund_dialog_title')}</AlertDialogTitle>
                      <AlertDialogDescription>{t('refund_dialog_desc')}</AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                      <AlertDialogAction onClick={handleRefund}>
                        {t('refund_dialog_confirm')}
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              )}

              {/* Resend receipt — available for guest or registered user purchases */}
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="secondary" size="sm" disabled={loading === 'resend'}>
                    {loading === 'resend' ? tCommon('loading') : t('action_resend_receipt')}
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>{t('resend_dialog_title')}</AlertDialogTitle>
                    <AlertDialogDescription>{t('resend_dialog_desc')}</AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
                    <AlertDialogAction onClick={handleResendReceipt}>
                      {t('resend_dialog_confirm')}
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </Stack>
          </Card>
        </div>
      </div>
    </div>
  );
}
