import { useQuery } from '@tanstack/react-query';
import { Download } from 'lucide-react';
import { toast } from 'sonner';

import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { formatDate } from '@/lib/dateUtils';
import { describeSourceFileExtractionStatus } from '@/lib/sourceFileExtractionStatus';
import { formatFileSize } from '@/lib/sourceFileUtils';
import { isSupabaseConfigured } from '@/lib/supabase';
import {
  createSourceFileDownloadUrl,
  listSourceFiles,
} from '@/services/sourceFileService';
import type { SourceFileRecord } from '@/types';

import { getFileIcon, renderUploadError } from '../lib/materialHelpers';

interface SourceFileViewDialogProps {
  batchId: string | null;
  open: boolean;
  onClose: () => void;
}

export function SourceFileViewDialog({ batchId, open, onClose }: SourceFileViewDialogProps) {
  const sourceFilesQuery = useQuery({
    queryKey: ['materials-source-files', batchId],
    queryFn: () => listSourceFiles(batchId ?? undefined),
    enabled: open && Boolean(batchId) && isSupabaseConfigured(),
  });

  async function handleDownload(record: SourceFileRecord) {
    try {
      const signedUrl = await createSourceFileDownloadUrl(record.storage_path);
      window.open(signedUrl, '_blank', 'noopener,noreferrer');
    } catch (error) {
      toast.error(renderUploadError(error));
    }
  }

  return (
    <Dialog open={open} onOpenChange={nextOpen => { if (!nextOpen) onClose(); }}>
      <DialogContent className="max-w-lg max-h-[70vh] flex flex-col gap-0 p-0">
        <DialogHeader className="px-6 py-4 border-b shrink-0">
          <DialogTitle className="text-base font-semibold">原始文件</DialogTitle>
          {batchId && (
            <p className="text-xs text-muted-foreground mt-0.5">批次：{batchId}</p>
          )}
        </DialogHeader>
        <div className="flex-1 overflow-auto px-4 py-3 space-y-2">
          {!batchId ? (
            <p className="text-sm text-muted-foreground text-center py-10">未选择批次</p>
          ) : !isSupabaseConfigured() ? (
            <p className="text-sm text-muted-foreground text-center py-10">请先配置 Supabase 环境变量</p>
          ) : sourceFilesQuery.isLoading ? (
            <p className="text-sm text-muted-foreground text-center py-10">正在读取原始文件...</p>
          ) : sourceFilesQuery.isError ? (
            <p className="text-sm text-destructive text-center py-10">{renderUploadError(sourceFilesQuery.error)}</p>
          ) : (sourceFilesQuery.data?.length ?? 0) === 0 ? (
            <p className="text-sm text-muted-foreground text-center py-10">暂无上传文件</p>
          ) : (
            sourceFilesQuery.data?.map(record => {
              const { Icon, iconClass, badge, badgeClass } = getFileIcon(record.file_name);
              const extractionStatus = describeSourceFileExtractionStatus(record);
              return (
                <div key={record.id} className="flex items-center gap-3 px-4 py-3 rounded-lg border border-border hover:bg-muted/30 transition-colors group">
                  <Icon className={`h-8 w-8 shrink-0 ${iconClass}`} />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium truncate">{record.file_name}</span>
                      <span className={`text-xs px-1.5 py-0.5 rounded border shrink-0 ${badgeClass}`}>{badge}</span>
                      <span className={`text-xs px-1.5 py-0.5 rounded border shrink-0 ${extractionStatus.badgeClassName}`}>{extractionStatus.label}</span>
                    </div>
                    <div className="flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground">
                      <span>{formatFileSize(record.size_bytes)}</span>
                      <span>·</span>
                      <span>{formatDate(record.uploaded_at)}</span>
                      <span>·</span>
                      <span>{record.uploaded_by || '未填写'}</span>
                    </div>
                    {extractionStatus.detail && (
                      <p className="mt-0.5 truncate text-xs text-muted-foreground">{extractionStatus.detail}</p>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => handleDownload(record)}
                    className="flex items-center gap-1 text-xs text-blue-600 hover:text-blue-700 opacity-0 group-hover:opacity-100 transition-opacity shrink-0"
                  >
                    <Download className="h-3.5 w-3.5" />下载
                  </button>
                </div>
              );
            })
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
