// @design-system: domain/DraftsList
'use client';

import { useEffect, useState } from 'react';
import { useQuery, useQueryClient } from '@/features/query/react-query';
import { HydratedIsland } from '@/components/HydratedIsland';
import { DraftDealCard } from '@/components/ui/domain/DealCard';
import { Skeleton } from '@/components/ui/feedback/Skeleton';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { Button } from '@/components/ui/primitives/Button';
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogAction,
  AlertDialogCancel,
} from '@/components/ui/overlays/AlertDialog';
import { useToast } from '@/components/ui/overlays/Toast/useToast';
import { useT } from '@/lib/i18n/react';
import { interpolate } from '@/lib/i18n/interpolate';
import { getCsrfToken } from '@/lib/csrf';
import { captureCaught } from '@/lib/observability';
import { cn } from '@/lib/cn';
import { fetchWithRefresh } from '@/lib/api/refresh-on-401';
import { ErrorBoundary } from '@/components/ui/feedback/ErrorBoundary';
import { qk } from '@/lib/query/keys';
import { VendorShell } from '@/components/ui/layout/VendorShell';

export interface DraftSummary {
  id: string;
  title: string | null;
  updatedAt: string;
  isStarred: boolean;
}

export interface DraftsListProps {
  className?: string;
  bare?: boolean;
}

const QUERY_KEY = qk.vendorDrafts();

async function fetchDrafts(): Promise<DraftSummary[]> {
  const res = await fetchWithRefresh('/api/vendor/deals/drafts');
  if (!res.ok) throw new Error('fetch-failed');
  const body = (await res.json()) as { drafts: DraftSummary[] };
  return body.drafts;
}

async function toggleStar(id: string): Promise<void> {
  const res = await fetchWithRefresh(`/api/vendor/deals/drafts/${id}/star`, {
    method: 'POST',
    headers: { 'x-csrf-token': getCsrfToken() },
  });
  if (!res.ok) throw new Error('star-failed');
}

async function deleteDraft(id: string): Promise<void> {
  const res = await fetchWithRefresh(`/api/vendor/deals/drafts/${id}`, {
    method: 'DELETE',
    headers: { 'x-csrf-token': getCsrfToken() },
  });
  if (!res.ok) throw new Error('delete-failed');
}

function DraftsListSkeleton() {
  return (
    <ul aria-busy="true" className="flex flex-col gap-3">
      {(['skeleton-1', 'skeleton-2', 'skeleton-3'] as const).map((skeletonKey) => (
        <li key={skeletonKey}>
          <Skeleton className="h-28 w-full rounded-2xl" />
        </li>
      ))}
    </ul>
  );
}

function DraftsListInner({ className }: DraftsListProps) {
  const t = useT('vendorDrafts');
  const tCommon = useT('common');
  const { toast } = useToast();
  const qc = useQueryClient();
  const [pendingDelete, setPendingDelete] = useState<DraftSummary | null>(null);
  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: QUERY_KEY,
    queryFn: fetchDrafts,
  });

  useEffect(() => {
    if (!isLoading) {
      document.getElementById('drafts-island-root')?.removeAttribute('aria-busy');
    }
  }, [isLoading]);

  const invalidate = () => qc.invalidateQueries({ queryKey: QUERY_KEY });

  const handleDeleteConfirm = async () => {
    if (!pendingDelete) return;
    const id = pendingDelete.id;
    setPendingDelete(null);
    try {
      await deleteDraft(id);
      await invalidate();
    } catch (err) {
      captureCaught(err, { scope: 'components.DraftsList.delete', severity: 'warning' });
      toast({ title: tCommon('error_save'), tone: 'danger' });
    }
  };

  if (isLoading) return <DraftsListSkeleton />;

  if (isError) {
    return (
      <ErrorState
        title={t('loadError')}
        action={
          <Button variant="secondary" size="sm" onClick={() => refetch()}>
            {tCommon('retry')}
          </Button>
        }
      />
    );
  }

  if (!data || data.length === 0) {
    return (
      <div className="flex flex-col items-center gap-4 py-12 text-center">
        <p className="text-text-secondary text-base">{t('emptyDrafts')}</p>
        <Button variant="primary" size="md" asChild>
          <a href="/vendor/deals/new">{t('createNewDeal')}</a>
        </Button>
      </div>
    );
  }

  return (
    <ErrorBoundary>
      <ul className={cn('flex flex-col gap-3', className)}>
        {data.map((draft) => (
          <li key={draft.id}>
            <DraftDealCard
              id={draft.id}
              title={draft.title}
              updatedAt={draft.updatedAt}
              isStarred={draft.isStarred}
              onToggleStar={async () => {
                await toggleStar(draft.id);
                await invalidate();
              }}
              onResume={() => {
                window.location.href = `/vendor/deals/new?draftId=${draft.id}`;
              }}
              onDelete={() => setPendingDelete(draft)}
            />
          </li>
        ))}
      </ul>

      <AlertDialog
        open={pendingDelete != null}
        onOpenChange={(open) => !open && setPendingDelete(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t('deleteConfirmAction')}</AlertDialogTitle>
            <AlertDialogDescription>
              {interpolate(t('deleteConfirm'), {
                title: pendingDelete?.title?.trim() || t('untitled'),
              })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{tCommon('cancel')}</AlertDialogCancel>
            <AlertDialogAction onClick={() => void handleDeleteConfirm()}>
              {t('deleteConfirmAction')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </ErrorBoundary>
  );
}

export function DraftsList({ bare = false, ...props }: DraftsListProps) {
  const t = useT('vendorDrafts');
  const inner = (
    <HydratedIsland>
      <DraftsListInner {...props} />
    </HydratedIsland>
  );

  if (bare) return inner;

  return (
    <VendorShell variant="dashboard" currentPath="/vendor/deals/drafts">
      <div className="flex flex-col gap-6 p-4 lg:p-6">
        <header>
          <h1 className="text-text-primary text-2xl font-bold">{t('drafts')}</h1>
          <p className="text-text-secondary mt-1 text-sm">{t('pageSubtitle')}</p>
        </header>
        {inner}
      </div>
    </VendorShell>
  );
}
