// src/features/admin-vendor-mgmt/VendorMgmt.tsx
// Admin: vendor list - filter by tier/state/search, click row to drill into /admin/vendors/[id].
// Freeze and unfreeze remain as inline table actions; ban/upgrade/activate move to the detail page.

'use client';

import { useState } from 'react';
import { getCsrfToken } from '@/lib/csrf';
import { Switch } from '@/components/ui/primitives/Switch';
import { useT } from '@/lib/i18n/react';
import { formatAgorotCurrencyILS } from '@/lib/money';
import { usePaginatedQuery } from '@/lib/hooks/usePaginatedQuery';
import { AdminListPage } from '@/components/ui/domain/admin/AdminListPage';
import {
  AdminTable,
  type ColumnDef,
  type ActionDef,
} from '@/components/ui/domain/admin/AdminTable';
import { AdminFilterBar, type FilterChip } from '@/components/ui/domain/admin/AdminFilterBar';
import { Pagination } from '@/components/ui/primitives/Pagination';
import { useAdminFilters } from '@/components/ui/domain/admin/AdminFilterBar/useAdminFilters';
import { Pill } from '@/components/ui/primitives/Pill';
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogAction,
  AlertDialogCancel,
} from '@/components/ui/overlays/AlertDialog';
import { FreezeDialog } from '@/components/ui/overlays/FreezeDialog';
import { ErrorBoundary } from '@/components/ui/feedback/ErrorBoundary';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { AdminListPageSkeleton } from '@/components/ui/feedback/Skeleton';
import { formatDate } from '@/lib/format';
import { Button } from '@/components/ui/primitives/Button';
import { QueryBoundary } from '@platform-modules/ui-primitives';

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

export interface VendorRow {
  id: string;
  businessName: string;
  displayName: string;
  tier: string;
  accountState: string;
  flagReason: string | null;
  rejectReason: string | null;
  llmDecision: string | null;
  totalSales: number;
  totalRevenue: string;
  reviewsScore: string;
  reviewsCount: number;
  activeDeals: number;
  createdAt: string;
}

export interface VendorMgmtProps {
  initialVendors: VendorRow[];
  initialTotal: number;
  initialPage?: number;
}

// ─── Filter param keys ────────────────────────────────────────────────────────

const FILTER_KEYS = ['state', 'tier', 'search', 'hideNoDeals'];

// ─── Tone helpers ─────────────────────────────────────────────────────────────

type PillTone = 'success' | 'warning' | 'danger' | 'neutral' | 'info';

function stateTone(state: string, flagReason: string | null): PillTone {
  if (state === 'ACTIVE') return 'success';
  if (state === 'VETERAN') return 'info';
  if (state === 'FROZEN') return 'warning';
  if (state === 'BANNED') return 'danger';
  if (state === 'REJECTED') return 'danger';
  if (state === 'PENDING_FIRST_APPROVAL' && flagReason) return 'warning'; // FLAGGED
  if (state === 'PENDING_FIRST_APPROVAL') return 'neutral';
  if (state === 'PENDING_PROCESSOR') return 'neutral';
  return 'neutral';
}

function tierTone(tier: string): PillTone {
  return tier === 'VETERAN' ? 'info' : 'neutral';
}

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

export function VendorMgmt({ initialVendors, initialTotal, initialPage }: VendorMgmtProps) {
  const t = useT('admin_vendors');
  const tCommon = useT('common');

  // ── Read active filter values from URL params ─────────────────────────────
  const { filters, setFilter } = useAdminFilters(FILTER_KEYS);
  const stateFilter = filters['state'] ?? '';
  const tierFilter = filters['tier'] ?? '';
  const searchFilter = filters['search'] ?? '';
  // Default: hide vendors with 0 active deals. 'false' in URL = show them.
  const hideNoDeals = filters['hideNoDeals'] !== 'false';

  const params: Record<string, string> = {};
  if (stateFilter) params.state = stateFilter;
  if (tierFilter) params.tier = tierFilter;
  if (searchFilter) params.search = searchFilter;
  params.hideNoDeals = String(hideNoDeals);

  // ── Paginated data ─────────────────────────────────────────────────────────
  const {
    data,
    totalPages,
    page,
    isInitialLoading,
    isRefetching,
    isLoading: _isLoading,
    error,
    setPage,
    refetch,
  } = usePaginatedQuery<VendorRow>({
    endpoint: '/api/admin/vendors',
    params,
    limit: 12,
    initialData: initialVendors,
    initialTotal,
    initialPage,
    dataKey: 'vendors',
  });

  // ── Freeze dialog state ───────────────────────────────────────────────────
  const [freezeVendorId, setFreezeVendorId] = useState<string | null>(null);

  // ── Unfreeze confirm dialog state ─────────────────────────────────────────
  const [unfreezeVendorId, setUnfreezeVendorId] = useState<string | null>(null);

  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [actionError, setActionError] = useState<string | null>(null);

  // ── Action helpers ────────────────────────────────────────────────────────

  async function postAction(vendorId: string, segment: string, body?: object) {
    setActionLoading(vendorId);
    setActionError(null);
    try {
      const res = await fetch(`/api/admin/vendors/${vendorId}/${segment}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-csrf-token': getCsrfToken() },
        body: body ? JSON.stringify(body) : undefined,
      });
      if (!res.ok) throw new Error(await res.text());
      refetch();
    } catch (err) {
      setActionError(err instanceof Error ? err.message : String(err));
    } finally {
      setActionLoading(null);
    }
  }

  async function handleUnfreezeConfirm() {
    if (!unfreezeVendorId) return;
    await postAction(unfreezeVendorId, 'unfreeze');
    setUnfreezeVendorId(null);
  }

  // ── State / Tier chips ───────────────────────────────────────────────────
  const stateChips: FilterChip[] = [
    {
      key: 'state',
      value: 'PENDING_FIRST_APPROVAL',
      label: t('state_pending'),
      groupLabel: t('filter_state'),
    },
    {
      key: 'state',
      value: 'PENDING_PROCESSOR',
      label: t('state_pending_processor'),
      groupLabel: t('filter_state'),
    },
    {
      key: 'state',
      value: 'FLAGGED',
      label: t('state_flagged'),
      groupLabel: t('filter_state'),
    },
    { key: 'state', value: 'ACTIVE', label: t('state_active'), groupLabel: t('filter_state') },
    { key: 'state', value: 'VETERAN', label: t('state_veteran'), groupLabel: t('filter_state') },
    { key: 'state', value: 'FROZEN', label: t('state_frozen'), groupLabel: t('filter_state') },
    { key: 'state', value: 'BANNED', label: t('state_banned'), groupLabel: t('filter_state') },
    { key: 'state', value: 'REJECTED', label: t('state_rejected'), groupLabel: t('filter_state') },
    { key: 'tier', value: 'NEW', label: t('tier_new_chip'), groupLabel: t('filter_tier') },
    { key: 'tier', value: 'VETERAN', label: t('tier_veteran_chip'), groupLabel: t('filter_tier') },
  ];

  // ── Column definitions ────────────────────────────────────────────────────
  const columns: ColumnDef<VendorRow>[] = [
    {
      key: 'businessName',
      label: t('col_business_name'),
      render: (r) => (
        <span className="text-text-primary font-medium">
          {r.businessName ?? r.displayName ?? ''}
        </span>
      ),
    },
    {
      key: 'tier',
      label: t('col_tier'),
      render: (r) => (
        <Pill tone={tierTone(r.tier)} size="sm">
          {r.tier === 'VETERAN' ? t('tier_veteran') : t('tier_new')}
        </Pill>
      ),
    },
    {
      key: 'accountState',
      label: t('col_state'),
      render: (r) => {
        const isVirtualFlagged =
          r.accountState === 'PENDING_FIRST_APPROVAL' && (r.flagReason ?? null) != null;
        const labelMap: Record<string, string> = {
          PENDING_FIRST_APPROVAL: isVirtualFlagged ? t('state_flagged') : t('state_pending'),
          PENDING_PROCESSOR: t('state_pending_processor'),
          ACTIVE: t('state_active'),
          VETERAN: t('state_veteran'),
          FROZEN: t('state_frozen'),
          BANNED: t('state_banned'),
          REJECTED: t('state_rejected'),
        };
        return (
          <Pill tone={stateTone(r.accountState, r.flagReason ?? null)} size="sm">
            {labelMap[r.accountState] ?? r.accountState}
          </Pill>
        );
      },
    },
    {
      key: 'activeDeals',
      label: t('col_active_deals'),
      headerTooltip: t('col_active_deals_tooltip'),
      align: 'end',
      render: (r) => String(r.activeDeals ?? 0),
    },
    {
      key: 'totalSales',
      label: t('col_sales'),
      headerTooltip: t('col_sales_tooltip'),
      align: 'end',
      render: (r) => String(r.totalSales ?? 0),
    },
    {
      key: 'totalRevenue',
      label: t('col_revenue'),
      headerTooltip: t('col_revenue_tooltip'),
      align: 'end',
      render: (r) => formatAgorotCurrencyILS(Math.round(parseFloat(r.totalRevenue ?? '0') * 100)),
    },
    {
      key: 'reviewsScore',
      label: t('col_score'),
      headerTooltip: t('col_score_tooltip'),
      align: 'end',
      render: (r) =>
        (r.reviewsCount ?? 0) > 0 ? parseFloat(r.reviewsScore ?? '0').toFixed(1) : '—',
    },
    {
      key: 'createdAt',
      label: t('col_created'),
      render: (r) => formatDate(r.createdAt, 'he'),
    },
  ];

  // ── Action definitions (freeze / unfreeze inline only) ────────────────────
  const actions: ActionDef<VendorRow>[] = [
    {
      key: 'freeze',
      label: t('freeze_confirm_action'),
      variant: 'danger',
      hidden: (r) => r.accountState === 'FROZEN' || r.accountState === 'BANNED',
      onAction: (r) => {
        setFreezeVendorId(r.id);
      },
    },
    {
      key: 'unfreeze',
      label: t('unfreeze_confirm_action'),
      hidden: (r) => r.accountState !== 'FROZEN',
      onAction: (r) => setUnfreezeVendorId(r.id),
    },
  ];

  const vendorsQuery = {
    data: isInitialLoading ? undefined : { rows: data, totalPages, page },
    isLoading: isInitialLoading,
    isPending: isInitialLoading,
    isError: Boolean(error),
    error: error ? new Error(error) : null,
    refetch,
  };

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <ErrorBoundary>
      <>
        <QueryBoundary
          query={vendorsQuery}
          skeleton={<AdminListPageSkeleton filterRows={2} tableCols={9} />}
          errorFallback={() => (
            <ErrorState
              title={tCommon('error_loading')}
              action={
                <Button variant="secondary" size="sm" onClick={() => refetch()}>
                  {tCommon('retry')}
                </Button>
              }
            />
          )}
        >
          {(resolved) => (
            <AdminListPage
              busy={isRefetching}
              filterBar={
                <div className="flex flex-col gap-3">
                  <AdminFilterBar
                    chips={stateChips}
                    searchKey="search"
                    suggestions={resolved.rows.map((v) => ({ id: v.id, label: v.businessName }))}
                  />
                  <label className="flex w-fit cursor-pointer items-center gap-2">
                    <Switch
                      checked={!hideNoDeals}
                      onCheckedChange={(checked) =>
                        setFilter('hideNoDeals', checked ? 'false' : '')
                      }
                    />
                    <span
                      className="text-text-secondary text-sm"
                      title={t('show_no_deals_toggle_tooltip')}
                    >
                      {t('show_no_deals_toggle')}
                    </span>
                  </label>
                </div>
              }
              table={
                <AdminTable<VendorRow>
                  columns={columns}
                  rows={resolved.rows}
                  rowHref={(r) => `/admin/vendors/${r.id}`}
                  actions={actions}
                />
              }
              pagination={
                resolved.totalPages > 1 ? (
                  <Pagination
                    page={resolved.page}
                    totalPages={resolved.totalPages}
                    onPageChange={setPage}
                  />
                ) : undefined
              }
            />
          )}
        </QueryBoundary>

        {actionError && (
          <p role="alert" className="text-danger-600 mt-2 text-sm">
            {actionError}
          </p>
        )}

        {/* Freeze confirm dialog — shared component, role="dialog" for E2E */}
        <FreezeDialog
          entityType="vendor"
          entityId={freezeVendorId ?? ''}
          isOpen={freezeVendorId !== null}
          onClose={() => setFreezeVendorId(null)}
          onSuccess={() => {
            setFreezeVendorId(null);
            refetch();
          }}
          showDuration
        />

        {/* Unfreeze confirm alert */}
        <AlertDialog
          open={unfreezeVendorId !== null}
          onOpenChange={(open) => {
            if (!open) setUnfreezeVendorId(null);
          }}
        >
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>{t('unfreeze_confirm_title')}</AlertDialogTitle>
              <AlertDialogDescription>{t('unfreeze_confirm_body')}</AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleUnfreezeConfirm}
                disabled={actionLoading === unfreezeVendorId}
              >
                {t('unfreeze_confirm_action')}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </>
    </ErrorBoundary>
  );
}
