'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Loader2, RefreshCw, FileText } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api/client';

interface InvoicePdfPreviewProps {
  invoiceId: string;
  pdfFileId?: string | null;
}

export function InvoicePdfPreview({ invoiceId, pdfFileId: initialPdfFileId }: InvoicePdfPreviewProps) {
  const queryClient = useQueryClient();
  const [pdfFileId, setPdfFileId] = useState(initialPdfFileId);

  const { data: previewData, isLoading: previewLoading } = useQuery<{ url: string; mimeType: string }>({
    queryKey: ['file-preview', pdfFileId],
    queryFn: () => apiFetch(`/api/v1/files/${pdfFileId}/preview`),
    enabled: !!pdfFileId,
  });

  const regenerateMutation = useMutation({
    mutationFn: () =>
      apiFetch<{ data?: { id?: string } }>(`/api/v1/invoices/${invoiceId}/generate-pdf`, { method: 'POST' }),
    onSuccess: (data) => {
      const fileId = data?.data?.id;
      if (fileId) {
        setPdfFileId(fileId);
        queryClient.invalidateQueries({ queryKey: ['invoices', invoiceId] });
        queryClient.invalidateQueries({ queryKey: ['file-preview', fileId] });
      }
    },
  });

  if (!pdfFileId) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 py-12 border border-dashed rounded-md">
        <FileText className="h-10 w-10 text-muted-foreground" />
        <p className="text-sm text-muted-foreground">No PDF generated yet</p>
        <Button
          variant="outline"
          size="sm"
          onClick={() => regenerateMutation.mutate()}
          disabled={regenerateMutation.isPending}
        >
          {regenerateMutation.isPending ? (
            <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
          ) : (
            <RefreshCw className="mr-1.5 h-4 w-4" />
          )}
          Generate PDF
        </Button>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-end">
        <Button
          variant="outline"
          size="sm"
          onClick={() => regenerateMutation.mutate()}
          disabled={regenerateMutation.isPending}
        >
          {regenerateMutation.isPending ? (
            <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
          ) : (
            <RefreshCw className="mr-1.5 h-4 w-4" />
          )}
          Regenerate PDF
        </Button>
      </div>

      {previewLoading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
        </div>
      ) : previewData?.url ? (
        <iframe
          src={previewData.url}
          className="w-full rounded border"
          style={{ height: '600px' }}
          title="Invoice PDF"
        />
      ) : (
        <div className="flex items-center justify-center py-12 border rounded">
          <p className="text-sm text-muted-foreground">Unable to load PDF preview</p>
        </div>
      )}
    </div>
  );
}
