// src/features/admin-reports/ReportsQueue.tsx
// Admin: report tickets queue - filter by status/targetType.
// Inline actions: Dismiss (AlertDialog), Investigate, Resolve (Dialog).

'use client';

import { useState } from 'react';
import { getCsrfToken } from '@/lib/csrf';
import { useT, useLocale } from '@/lib/i18n/react';
import { interpolate } from '@/lib/i18n/interpolate';
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 {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/overlays/Dialog';
import { Textarea } from '@/components/ui/primitives/Textarea';
import { Label } from '@/components/ui/primitives/Label';
import { Button } from '@/components/ui/primitives/Button';
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 { QueryBoundary } from '@platform-modules/ui-primitives';

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

export interface ReportTicketRow {
  id: string;
  reporterUserId: string | null;
  targetType: string;
  targetId: string;
  reason: string;
  body: string;
  status: string;
  createdAt: string;
  resolvedAt: string | null;
  heSlug?: string | null;
}

export interface ReportsQueueProps {
  initialReports: ReportTicketRow[];
  initialTotal: number;
  initialPage?: number;
}

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

const FILTER_KEYS = ['status', 'targetType'];
const PAGE_LIMIT = 20;

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

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

function statusTone(status: string): PillTone {
  if (status === 'OPEN') return 'danger';
  if (status === 'INVESTIGATING') return 'warning';
  if (status === 'RESOLVED') return 'success';
  return 'neutral';
}

function buildEntityUrl(
  targetType: string,
  targetId: string,
  heSlug?: string | null,
): string | null {
  switch (targetType) {
    case 'VENDOR':
      return `/vendor/${targetId}`;
    case 'DEAL':
      return heSlug ? `/deals/${heSlug}` : '/deals';
    case 'REVIEW':
      return `/vendor/${targetId}#reviews`;
    case 'USER':
      return null;
    default:
      return null;
  }
}

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

export function ReportsQueue({ initialReports, initialTotal, initialPage }: ReportsQueueProps) {
  const t = useT('admin_reports');
  const tList = useT('admin_list');
  const tCommon = useT('common');
  const { locale } = useLocale();

  // ── Read active filter values from URL params ─────────────────────────────
  const { filters } = useAdminFilters(FILTER_KEYS);
  const statusFilter = filters['status'] ?? '';
  const targetTypeFilter = filters['targetType'] ?? '';

  const params: Record<string, string> = {};
  if (statusFilter) params.status = statusFilter;
  if (targetTypeFilter) params.targetType = targetTypeFilter;

  // ── Paginated data ─────────────────────────────────────────────────────────
  const { data, totalPages, page, isInitialLoading, isRefetching, error, setPage, refetch, total } =
    usePaginatedQuery<ReportTicketRow>({
      endpoint: '/api/admin/reports',
      params,
      limit: PAGE_LIMIT,
      initialData: initialReports,
      initialTotal,
      initialPage,
      dataKey: 'reports',
    });

  // ── Resolve dialog state ───────────────────────────────────────────────────
  const [resolveId, setResolveId] = useState<string | null>(null);
  const [resolution, setResolution] = useState('');

  // ── Dismiss alert dialog state ─────────────────────────────────────────────
  const [dismissId, setDismissId] = useState<string | null>(null);

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

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

  async function postAction(reportId: string, segment: string, body?: object) {
    setActionLoading(reportId);
    setActionError(null);
    try {
      const res = await fetch(`/api/admin/reports/${reportId}/${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 handleInvestigate(reportId: string) {
    await postAction(reportId, 'investigate');
  }

  async function handleResolveSubmit() {
    if (!resolveId || !resolution.trim()) return;
    await postAction(resolveId, 'resolve', { resolution: resolution.trim() });
    setResolveId(null);
    setResolution('');
  }

  async function handleDismissConfirm() {
    if (!dismissId) return;
    await postAction(dismissId, 'dismiss');
    setDismissId(null);
  }

  // ── Chips ─────────────────────────────────────────────────────────────────
  const statusChips: FilterChip[] = [
    { key: 'status', value: 'OPEN', label: t('status_open'), groupLabel: t('filter_status') },
    {
      key: 'status',
      value: 'INVESTIGATING',
      label: t('status_investigating'),
      groupLabel: t('filter_status'),
    },
    {
      key: 'status',
      value: 'RESOLVED',
      label: t('status_resolved'),
      groupLabel: t('filter_status'),
    },
    {
      key: 'status',
      value: 'DISMISSED',
      label: t('status_dismissed'),
      groupLabel: t('filter_status'),
    },
    {
      key: 'targetType',
      value: 'VENDOR',
      label: t('target_type_vendor'),
      groupLabel: t('filter_target_type'),
    },
    {
      key: 'targetType',
      value: 'DEAL',
      label: t('target_type_deal'),
      groupLabel: t('filter_target_type'),
    },
    {
      key: 'targetType',
      value: 'REVIEW',
      label: t('target_type_review'),
      groupLabel: t('filter_target_type'),
    },
    {
      key: 'targetType',
      value: 'USER',
      label: t('target_type_user'),
      groupLabel: t('filter_target_type'),
    },
  ];

  // ── Column definitions ────────────────────────────────────────────────────
  const reasonMap: Record<string, string> = {
    FACTUAL_ERROR: t('reason_factual_error'),
    MISLEADING: t('reason_misleading'),
    WRONG_HOURS: t('reason_wrong_hours'),
    BUG: t('reason_bug'),
    OTHER: t('reason_other'),
  };

  const targetTypeMap: Record<string, string> = {
    VENDOR: t('target_type_vendor'),
    DEAL: t('target_type_deal'),
    REVIEW: t('target_type_review'),
    USER: t('target_type_user'),
  };

  const statusLabelMap: Record<string, string> = {
    OPEN: t('status_open'),
    INVESTIGATING: t('status_investigating'),
    RESOLVED: t('status_resolved'),
    DISMISSED: t('status_dismissed'),
  };

  const statusTooltipMap: Record<string, string> = {
    OPEN: t('status_tooltip_open'),
    INVESTIGATING: t('status_tooltip_investigating'),
    RESOLVED: t('status_tooltip_resolved'),
    DISMISSED: t('status_tooltip_dismissed'),
  };

  const columns: ColumnDef<ReportTicketRow>[] = [
    {
      key: 'createdAt',
      label: t('col_date'),
      render: (r) => formatDate(r.createdAt, locale),
    },
    {
      key: 'targetType',
      label: t('col_target_type'),
      render: (r) => {
        const entityUrl = buildEntityUrl(r.targetType, r.targetId, r.heSlug);
        const label = targetTypeMap[r.targetType] ?? r.targetType;
        return entityUrl ? (
          <a
            href={entityUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="text-brand-primary-600 hover:text-brand-primary-800 underline"
          >
            {label}
          </a>
        ) : (
          <span>{label}</span>
        );
      },
    },
    {
      key: 'reason',
      label: t('col_reason'),
      render: (r) => reasonMap[r.reason] ?? r.reason,
    },
    {
      key: 'status',
      label: t('col_status'),
      render: (r) => (
        <Pill tone={statusTone(r.status)} size="sm" title={statusTooltipMap[r.status]}>
          {statusLabelMap[r.status] ?? r.status}
        </Pill>
      ),
    },
    {
      key: 'reporterUserId',
      label: t('col_reporter'),
      render: (r) =>
        r.reporterUserId ? (
          <span data-diag className="font-mono text-xs">
            {r.reporterUserId.slice(0, 8)}…
          </span>
        ) : (
          <span className="text-text-secondary">{t('reporter_anonymous')}</span>
        ),
    },
  ];

  // ── Action definitions ────────────────────────────────────────────────────
  const actions: ActionDef<ReportTicketRow>[] = [
    {
      key: 'investigate',
      label: t('action_investigate'),
      hidden: (r) => r.status !== 'OPEN',
      onAction: (r) => handleInvestigate(r.id),
    },
    {
      key: 'resolve',
      label: t('action_resolve'),
      hidden: (r) => r.status !== 'OPEN' && r.status !== 'INVESTIGATING',
      onAction: (r) => {
        setResolveId(r.id);
        setResolution('');
      },
    },
    {
      key: 'dismiss',
      label: t('action_dismiss'),
      variant: 'danger',
      hidden: (r) => r.status !== 'OPEN' && r.status !== 'INVESTIGATING',
      onAction: (r) => setDismissId(r.id),
    },
  ];

  const rangeFrom = total > 0 ? (page - 1) * PAGE_LIMIT + 1 : 0;
  const rangeTo = Math.min(page * PAGE_LIMIT, total);
  const rangeLabel =
    total > 0
      ? interpolate(tList('showing_x_of_y'), { from: rangeFrom, to: rangeTo, total })
      : null;

  const reportsQuery = {
    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={reportsQuery}
          skeleton={<AdminListPageSkeleton tableCols={6} />}
          errorFallback={() => (
            <ErrorState
              title={tList('error_title')}
              description={tList('error_desc')}
              action={
                <Button variant="secondary" size="sm" onClick={() => refetch()}>
                  {tList('retry')}
                </Button>
              }
            />
          )}
        >
          {(resolved) => (
            <AdminListPage
              busy={isRefetching}
              filterBar={
                <div className="flex flex-col gap-2">
                  <AdminFilterBar chips={statusChips} />
                  {rangeLabel ? (
                    <p className="text-text-secondary text-xs" aria-live="polite">
                      {rangeLabel}
                    </p>
                  ) : null}
                </div>
              }
              table={
                <AdminTable<ReportTicketRow>
                  columns={columns}
                  rows={resolved.rows}
                  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>
        )}

        {/* Resolve dialog */}
        <Dialog
          open={resolveId !== null}
          onOpenChange={(open) => {
            if (!open) {
              setResolveId(null);
              setResolution('');
            }
          }}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t('action_resolve')}</DialogTitle>
            </DialogHeader>
            <div className="flex flex-col gap-1">
              <Label htmlFor="resolve-resolution">{t('resolve_label')}</Label>
              <Textarea
                id="resolve-resolution"
                rows={3}
                placeholder={t('resolve_placeholder')}
                value={resolution}
                onChange={(e) => setResolution(e.target.value)}
              />
            </div>
            <DialogFooter>
              <Button
                variant="primary"
                loading={actionLoading === resolveId}
                disabled={!resolution.trim()}
                onClick={handleResolveSubmit}
              >
                {t('action_resolve')}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* Dismiss confirm alert */}
        <AlertDialog
          open={dismissId !== null}
          onOpenChange={(open) => {
            if (!open) setDismissId(null);
          }}
        >
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>{t('dismiss_confirm_title')}</AlertDialogTitle>
              <AlertDialogDescription>{t('dismiss_confirm_body')}</AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
              <AlertDialogAction
                onClick={handleDismissConfirm}
                disabled={actionLoading === dismissId}
              >
                {t('dismiss_confirm_action')}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </>
    </ErrorBoundary>
  );
}
