import { useState } from 'react';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '../components/ui/button';
import type { InitiativeDraft } from './types';
import type { ContributionDraftShape } from './contributionDraftTypes';
import {
  createOfficialFormPdfFromDrafts,
  downloadPdfBlob,
} from './applicationFormOfficialPdf';
import {
  EMPTY_OFFICIAL_FORM_PREVIEW_FIELDS,
  type OfficialFormPreviewFields,
} from './officialFormPreviewFieldEdits';
import { OfficialFormPdfPreviewDialog } from './OfficialFormPdfPreviewDialog';

export type ApplicationFormOfficialPdfActionsProps = {
  draft: InitiativeDraft;
  contribution: ContributionDraftShape;
  caseId?: string;
  disabled?: boolean;
  className?: string;
};

/**
 * Preview (modal) + direct download for the official application-form PDF built in the browser.
 */
export function ApplicationFormOfficialPdfActions({
  draft,
  contribution,
  caseId,
  disabled = false,
  className,
}: ApplicationFormOfficialPdfActionsProps) {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [pdfBlob, setPdfBlob] = useState<Blob | null>(null);
  const [pdfFileName, setPdfFileName] = useState('');
  const [previewFields, setPreviewFields] = useState<OfficialFormPreviewFields>(EMPTY_OFFICIAL_FORM_PREVIEW_FIELDS);
  const [pdfSourceNote, setPdfSourceNote] = useState<string | null>(null);
  const [downloadLoading, setDownloadLoading] = useState(false);

  const handlePreviewOpen = () => {
    setPdfBlob(null);
    setPdfFileName('');
    setPreviewFields(EMPTY_OFFICIAL_FORM_PREVIEW_FIELDS);
    setPdfSourceNote(null);
    setPreviewOpen(true);
  };

  const handlePreview = async () => {
    if (previewLoading || disabled) return;
    setPreviewLoading(true);
    handlePreviewOpen();
    try {
      const { pdfBlob: blob, fileName, source, initialPreviewFields } = await createOfficialFormPdfFromDrafts(
        draft,
        contribution,
      );
      setPdfBlob(blob);
      setPdfFileName(fileName);
      setPreviewFields(initialPreviewFields);
      setPdfSourceNote(
        source === 'client'
          ? 'Bản xem trước: PDF tạo trong trình duyệt (docx-preview + canvas). Chỉnh sửa trường dữ liệu trong hộp thoại chỉ áp dụng cục bộ, không lưu lên máy chủ.'
          : 'Bản xem trước: PDF từ máy chủ (LibreOffice), cùng luồng với tệp official-form lưu ở MinIO khi nộp hồ sơ. Chỉnh sửa trường dữ liệu chỉ áp dụng cục bộ.',
      );
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Không xuất được PDF mẫu hồ sơ.';
      toast.error(msg);
      setPreviewOpen(false);
    } finally {
      setPreviewLoading(false);
    }
  };

  const handleDownload = async () => {
    if (downloadLoading || disabled) return;
    setDownloadLoading(true);
    try {
      const { pdfBlob: blob, fileName, source } = await createOfficialFormPdfFromDrafts(
        draft,
        contribution,
      );
      downloadPdfBlob(blob, fileName);
      toast.success(
        source === 'server'
          ? 'Đã tải PDF mẫu hồ sơ (LibreOffice, đồng bộ với máy chủ / MinIO).'
          : 'Đã tải PDF mẫu hồ sơ (trình duyệt — dự phòng khi máy chủ chưa cấu hình LibreOffice).',
      );
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Không xuất được PDF mẫu hồ sơ.';
      toast.error(msg);
    } finally {
      setDownloadLoading(false);
    }
  };

  const busy = previewLoading || downloadLoading;

  return (
    <>
      <div className={className ?? 'flex flex-wrap gap-2'}>
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="w-full sm:w-auto"
          onClick={() => void handlePreview()}
          disabled={disabled || busy}
        >
          {previewLoading ? (
            <>
              <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin inline" aria-hidden />
              Đang tạo PDF…
            </>
          ) : (
            'Xem trước PDF'
          )}
        </Button>
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="w-full sm:w-auto"
          onClick={() => void handleDownload()}
          disabled={disabled || busy}
        >
          {downloadLoading ? (
            <>
              <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin inline" aria-hidden />
              Đang tải PDF…
            </>
          ) : (
            'Xuất PDF (mẫu Word)'
          )}
        </Button>
      </div>

      <OfficialFormPdfPreviewDialog
        open={previewOpen}
        onOpenChange={(open) => {
          setPreviewOpen(open);
          if (!open) {
            setPdfBlob(null);
            setPdfFileName('');
            setPreviewFields(EMPTY_OFFICIAL_FORM_PREVIEW_FIELDS);
            setPdfSourceNote(null);
          }
        }}
        pdfBlob={pdfBlob}
        fileName={pdfFileName}
        initialPreviewFields={previewFields}
        loading={previewLoading}
        sourceNote={pdfSourceNote ?? undefined}
        caseId={caseId}
      />
    </>
  );
}
