
import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ApiService } from '../api';
import { HoSo, MauHoSo, TrangThaiHoSo, LoaiDuLieu } from '../types';

const JobDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [job, setJob] = useState<HoSo | null>(null);
  const [template, setTemplate] = useState<MauHoSo | null>(null);
  const [loading, setLoading] = useState(true);
  const [isOcrLoading, setIsOcrLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [showPrintModal, setShowPrintModal] = useState(false);
  const [selectedFile, setSelectedFile] = useState<{ name: string; path: string } | null>(null);

  const statusNames: Record<TrangThaiHoSo, string> = {
    [TrangThaiHoSo.BAN_NHAP]: 'Bản nháp',
    [TrangThaiHoSo.SAN_SANG_IN]: 'Sẵn sàng in',
    [TrangThaiHoSo.DA_IN]: 'Đã in',
    [TrangThaiHoSo.LUU_TRU]: 'Lưu trữ'
  };

  useEffect(() => {
    if (!id) return;
    const load = async () => {
      try {
        const j = await ApiService.getJobById(id);
        if (j) {
          setJob(j);
          try {
            const templates = await ApiService.getTemplates();
            setTemplate(templates.find(t => t.id === j.templateId) || null);
          } catch (err) {
            console.error('Error loading template:', err);
          }
        } else {
          alert('Không tìm thấy hồ sơ');
          navigate('/ho-so');
        }
      } catch (error: any) {
        console.error('Error loading job:', error);
        alert('Không thể tải hồ sơ: ' + (error.message || 'Lỗi không xác định'));
        navigate('/ho-so');
      } finally {
        setLoading(false);
      }
    };
    load();
  }, [id, navigate]);

  const handleOcr = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || !e.target.files.length || !job) return;
    setIsOcrLoading(true);
    const files = Array.from(e.target.files) as File[];
    try {
      const ocrResult = await ApiService.runOCR(files, job.templateId);

      // Log kết quả OCR để debug
      // console.log('=== OCR RESULT ===');
      // console.log('Result keys:', Object.keys(ocrResult.result || {}));
      // console.log('Result values:', ocrResult.result);
      // console.log('Confidence:', ocrResult.confidence);

      // Validate và normalize kết quả
      let normalizedResult: Record<string, any> = {};
      let normalizedConfidence: Record<string, number> = {};

      if (template) {
        template.fields.forEach(field => {
          const key = field.key;
          // AI đã được guide trả về đúng Key, fallback về rỗng nếu không có
          const value = ocrResult.result?.[key] || '';
          const conf = ocrResult.confidence?.[key] || 0;

          normalizedResult[key] = value;
          normalizedConfidence[key] = typeof conf === 'number' ? conf : parseFloat(conf) || 0;

          if (value) {
            // console.log(`[OCR Success] Field ${key}: "${value.substring(0, 30)}${value.length > 30 ? '...' : ''}" (conf: ${normalizedConfidence[key]})`);
          }
        });
      } else {
        normalizedResult = ocrResult.result || {};
        normalizedConfidence = ocrResult.confidence || {};
      }

      // console.log('Final Normalized Result:', normalizedResult);

      const fileObjects = await Promise.all(files.map(async f => ({
        name: f.name,
        path: await ApiService.fileToBase64(f)
      })));

      const updatedJob = {
        ...job,
        formData: { ...job.formData, ...normalizedResult },
        confidence: { ...job.confidence, ...normalizedConfidence },
        files: [...job.files, ...fileObjects]
      };
      setJob(updatedJob);
      await ApiService.saveJob(updatedJob);
      ApiService.log('Xử lý OCR', `Phân tích thành công ${files.length} tệp cho hồ sơ ${job.id}`).catch(console.error);
    } catch (error: any) {
      console.error('OCR Error:', error);
      alert('Lỗi xử lý OCR: ' + (error.message || 'Không thể xử lý tệp tin'));
    } finally {
      setIsOcrLoading(false);
    }
  };

  const updateField = (key: string, val: any) => {
    if (!job) return;
    setJob({ ...job, formData: { ...job.formData, [key]: val } });
  };

  const handleDeleteFile = async (index: number) => {
    if (!job) return;
    if (!confirm('Bạn có chắc chắn muốn xóa tệp này?')) return;

    const updatedFiles = [...job.files];
    updatedFiles.splice(index, 1);
    const updatedJob = { ...job, files: updatedFiles };

    try {
      await ApiService.saveJob(updatedJob);
      setJob(updatedJob);
      ApiService.log('Cập nhật hồ sơ', `Đã xóa 1 tệp đính kèm khỏi hồ sơ ${job.id}`).catch(console.error);
    } catch (error: any) {
      alert('Lỗi khi xóa tệp: ' + (error.message || 'Lỗi không xác định'));
    }
  };

  const handleSave = async (newStatus?: TrangThaiHoSo) => {
    if (!job || !template) return;

    // Validate required fields when approving
    if (newStatus === TrangThaiHoSo.SAN_SANG_IN) {
      const missingFields: string[] = [];
      template.fields.forEach(field => {
        if (field.required && (!job.formData[field.key] || job.formData[field.key].toString().trim() === '')) {
          missingFields.push(field.label);
        }
      });

      if (missingFields.length > 0) {
        alert(`Vui lòng điền đầy đủ các trường bắt buộc:\n${missingFields.join('\n')}`);
        return;
      }
    }

    setIsSaving(true);
    try {
      const finalJob = { ...job, trangThai: newStatus || job.trangThai, ngayCapNhat: new Date().toISOString() };
      const savedJob = await ApiService.saveJob(finalJob);
      setJob(savedJob);
      if (newStatus) {
        ApiService.log('Cập nhật hồ sơ', `Đã chuyển hồ sơ ${job.id} sang trạng thái ${statusNames[newStatus]}`).catch(console.error);
        if (newStatus === TrangThaiHoSo.DA_IN || newStatus === TrangThaiHoSo.LUU_TRU) {
          // Don't navigate away if just marking as printed or archived
          return;
        }
        navigate('/ho-so');
      } else {
        ApiService.log('Cập nhật hồ sơ', `Đã lưu bản nháp hồ sơ ${job.id}`).catch(console.error);
      }
    } catch (error: any) {
      alert('Lỗi lưu hồ sơ: ' + (error.message || 'Không thể lưu hồ sơ'));
    } finally {
      setIsSaving(false);
    }
  };

  if (loading) return <div className="flex items-center justify-center py-40"><div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div></div>;
  if (!job || !template) return <div className="text-center py-20 text-red-500 font-bold">Hồ sơ không tồn tại hoặc đã bị xóa.</div>;

  return (
    <div className="h-full flex flex-col space-y-6">
      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
        <div>
          <button onClick={() => navigate('/ho-so')} className="group flex items-center text-slate-400 hover:text-blue-600 font-black text-[10px] uppercase tracking-widest mb-2 transition-all">
            <svg className="w-4 h-4 mr-2 group-hover:-translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M15 19l-7-7 7-7" /></svg>
            Hành trình hồ sơ
          </button>
          <div className="flex items-center space-x-3">
            <h2 className="text-3xl font-black text-slate-800 dark:text-white tracking-tighter">Mã hồ sơ: {job.id}</h2>
            <span className={`px-3 py-1 rounded-full text-[10px] font-black uppercase ${job.trangThai === TrangThaiHoSo.SAN_SANG_IN ? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400' :
              job.trangThai === TrangThaiHoSo.DA_IN ? 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-400' :
                job.trangThai === TrangThaiHoSo.LUU_TRU ? 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300' :
                  'bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-400'
              }`}>
              {statusNames[job.trangThai] || job.trangThai.replace(/_/g, ' ')}
            </span>
          </div>
        </div>

        <div className="flex items-center space-x-3">
          <button
            disabled={isSaving}
            onClick={() => handleSave()}
            className="px-8 py-4 bg-white dark:bg-slate-800 border-2 border-slate-100 dark:border-slate-800 text-slate-600 dark:text-slate-300 font-black text-xs rounded-2xl hover:border-blue-500 transition-all active:scale-95 disabled:opacity-50"
          >
            {isSaving ? 'ĐANG LƯU...' : 'LƯU BẢN NHÁP'}
          </button>
          {job.trangThai === TrangThaiHoSo.BAN_NHAP && (
            <button
              disabled={isSaving}
              onClick={() => handleSave(TrangThaiHoSo.SAN_SANG_IN)}
              className="px-8 py-4 bg-blue-600 text-white font-black text-xs rounded-2xl shadow-2xl shadow-blue-500/30 hover:bg-blue-700 transition-all active:scale-95 disabled:opacity-50"
            >
              PHÊ DUYỆT & CHỐT IN
            </button>
          )}
          {job.trangThai === TrangThaiHoSo.SAN_SANG_IN && (
            <>
              <button
                disabled={isSaving}
                onClick={() => {
                  setShowPrintModal(true);
                }}
                className="px-8 py-4 bg-green-600 text-white font-black text-xs rounded-2xl shadow-2xl shadow-green-500/30 hover:bg-green-700 transition-all active:scale-95 disabled:opacity-50"
              >
                XEM TRƯỚC & IN
              </button>
              <button
                disabled={isSaving}
                onClick={() => handleSave(TrangThaiHoSo.DA_IN)}
                className="px-8 py-4 bg-purple-600 text-white font-black text-xs rounded-2xl shadow-2xl shadow-purple-500/30 hover:bg-purple-700 transition-all active:scale-95 disabled:opacity-50"
              >
                ĐÁNH DẤU ĐÃ IN
              </button>
              <button
                disabled={isSaving}
                onClick={() => handleSave(TrangThaiHoSo.LUU_TRU)}
                className="px-8 py-4 bg-slate-600 text-white font-black text-xs rounded-2xl shadow-2xl shadow-slate-500/30 hover:bg-slate-700 transition-all active:scale-95 disabled:opacity-50"
              >
                LƯU TRỮ
              </button>
            </>
          )}
        </div>
      </div>

      <div className="flex-1 grid grid-cols-1 lg:grid-cols-2 gap-8 min-h-0">
        <div className="bg-white dark:bg-slate-900 rounded-[2.5rem] border border-slate-100 dark:border-slate-800 flex flex-col overflow-hidden shadow-sm">
          <div className="p-6 bg-slate-50 dark:bg-slate-800/50 flex justify-between items-center border-b border-slate-100 dark:border-slate-800">
            <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Tệp đính kèm ({job.files.length})</span>
            <label className="px-4 py-2 bg-blue-600 text-white text-[10px] font-black rounded-xl cursor-pointer hover:bg-blue-700 transition-all shadow-lg shadow-blue-500/20">
              TẢI LÊN & OCR AI
              <input type="file" multiple className="hidden" onChange={handleOcr} />
            </label>
          </div>

          <div className="flex-1 p-8 overflow-y-auto custom-scrollbar relative">
            {isOcrLoading && (
              <div className="absolute inset-0 z-20 bg-white/60 dark:bg-slate-900/60 backdrop-blur-sm flex items-center justify-center">
                <div className="text-center">
                  <div className="w-16 h-16 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto mb-4 shadow-2xl shadow-blue-500/20"></div>
                  <p className="font-black text-slate-800 dark:text-white uppercase tracking-tighter text-sm">AI đang trích xuất dữ liệu...</p>
                </div>
              </div>
            )}

            {job.files.length > 0 ? (
              <div className="grid grid-cols-2 gap-4">
                {job.files.map((f, i) => {
                  const isImage = f.path.startsWith('data:image/');
                  const isPdf = f.path.startsWith('data:application/pdf') || f.name.toLowerCase().endsWith('.pdf');

                  return (
                    <div key={i} className="p-4 rounded-2xl bg-slate-50 dark:bg-slate-800/30 border border-slate-100 dark:border-slate-800 flex flex-col items-center group relative transition-all hover:shadow-xl hover:shadow-blue-500/5 hover:border-blue-200 dark:hover:border-blue-800">
                      <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex space-x-1">
                        <button
                          onClick={() => handleDeleteFile(i)}
                          className="p-1.5 bg-white dark:bg-slate-700 text-red-500 rounded-lg shadow-sm hover:bg-red-50 transition-colors"
                          title="Xóa tệp"
                        >
                          <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                        </button>
                      </div>

                      <div
                        onClick={() => setSelectedFile(f)}
                        className="w-12 h-12 bg-white dark:bg-slate-800 rounded-xl flex items-center justify-center mb-3 shadow-sm group-hover:rotate-6 transition-transform cursor-pointer"
                      >
                        {isImage ? (
                          <img src={f.path} alt={f.name} className="w-full h-full object-cover rounded-xl" />
                        ) : isPdf ? (
                          <span className="text-xl">📕</span>
                        ) : (
                          <span className="text-xl">📄</span>
                        )}
                      </div>
                      <p className="text-[10px] font-bold text-slate-500 break-all text-center line-clamp-2 px-1">{f.name}</p>

                      <div className="mt-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button
                          onClick={() => setSelectedFile(f)}
                          className="text-[9px] font-black text-blue-600 uppercase tracking-widest hover:underline"
                        >
                          Xem chi tiết
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="h-full flex flex-col items-center justify-center text-slate-300 border-4 border-dashed border-slate-50 dark:border-slate-800/50 rounded-[2rem]">
                <span className="text-6xl mb-4">📂</span>
                <p className="font-black uppercase tracking-widest text-xs">Chưa có tệp scan</p>
              </div>
            )}
          </div>
        </div>

        <div className="bg-white dark:bg-slate-900 rounded-[2.5rem] border border-slate-100 dark:border-slate-800 flex flex-col overflow-hidden shadow-sm">
          <div className="p-6 bg-slate-50 dark:bg-slate-800/50 flex justify-between items-center border-b border-slate-100 dark:border-slate-800">
            <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Dữ liệu hồ sơ động</span>
            <button onClick={() => setShowPrintModal(true)} className="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-xl transition-all"><svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg></button>
          </div>

          <div className="flex-1 p-8 overflow-y-auto custom-scrollbar space-y-6">
            {template.fields.map(field => {
              const conf = job.confidence[field.key] || 1;
              const isLow = conf < 0.75;
              return (
                <div key={field.key} className="space-y-2">
                  <div className="flex justify-between px-1">
                    <label className={`text-[11px] font-black uppercase tracking-widest ${field.required
                      ? 'text-slate-600 dark:text-slate-300'
                      : 'text-slate-400 dark:text-slate-500'
                      }`}>
                      {field.label} {field.required && <span className="text-red-500">*</span>}
                    </label>
                    {job.confidence[field.key] !== undefined && (
                      <span className={`text-[9px] font-bold px-2 py-0.5 rounded-lg ${isLow
                        ? 'text-orange-600 dark:text-orange-400 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800'
                        : 'text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'
                        }`}>
                        ⚡ AI Độ tin cậy: {Math.round(conf * 100)}%
                      </span>
                    )}
                  </div>
                  {field.type === LoaiDuLieu.VUNG_VAN_BAN ? (
                    <textarea
                      className={`w-full px-6 py-4 rounded-2xl border-2 transition-all outline-none focus:ring-4 font-bold text-sm ${isLow
                        ? 'border-orange-300 dark:border-orange-700 bg-orange-50 dark:bg-orange-900/30 focus:ring-orange-500/20 text-orange-900 dark:text-orange-100'
                        : 'border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/50 focus:ring-blue-500/20 dark:text-white'
                        }`}
                      rows={3}
                      value={job.formData[field.key] || ''}
                      onChange={(e) => updateField(field.key, e.target.value)}
                      placeholder={field.required ? `${field.label} *` : field.label}
                    />
                  ) : field.type === LoaiDuLieu.DAN_SACH ? (
                    <select
                      className={`w-full px-6 py-4 rounded-2xl border-2 transition-all outline-none focus:ring-4 font-bold text-sm ${isLow
                        ? 'border-orange-300 dark:border-orange-700 bg-orange-50 dark:bg-orange-900/30 focus:ring-orange-500/20 text-orange-900 dark:text-orange-100'
                        : 'border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/50 focus:ring-blue-500/20 dark:text-white'
                        }`}
                      value={job.formData[field.key] || ''}
                      onChange={(e) => updateField(field.key, e.target.value)}
                    >
                      <option value="">-- Chọn {field.label} --</option>
                      {field.options?.map(opt => (
                        <option key={opt} value={opt}>{opt}</option>
                      ))}
                    </select>
                  ) : (
                    <input
                      type={field.type === LoaiDuLieu.NGAY ? 'date' : field.type === LoaiDuLieu.SO ? 'number' : 'text'}
                      className={`w-full px-6 py-4 rounded-2xl border-2 transition-all outline-none focus:ring-4 font-bold text-sm ${isLow
                        ? 'border-orange-300 dark:border-orange-700 bg-orange-50 dark:bg-orange-900/30 focus:ring-orange-500/20 text-orange-900 dark:text-orange-100'
                        : 'border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/50 focus:ring-blue-500/20 dark:text-white'
                        }`}
                      value={job.formData[field.key] || ''}
                      onChange={(e) => updateField(field.key, e.target.value)}
                      placeholder={field.required ? `${field.label} *` : field.label}
                      required={field.required}
                    />
                  )}
                </div>
              )
            })}
          </div>
        </div>
      </div>

      {showPrintModal && (
        <div className="fixed inset-0 bg-slate-900/80 backdrop-blur-lg z-50 flex items-center justify-center p-4 md:p-8 animate-in fade-in duration-300">
          <div className="bg-white dark:bg-slate-900 w-full max-w-4xl h-full max-h-[90vh] rounded-[3rem] shadow-2xl flex flex-col overflow-hidden border border-slate-200 dark:border-slate-800">
            <div className="p-8 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/30">
              <div>
                <h3 className="text-2xl font-black text-slate-800 dark:text-white tracking-tighter">Xem trước Hồ sơ</h3>
                <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-1">Mã: {job.id} • {template.tenMau}</p>
              </div>
              <button onClick={() => setShowPrintModal(false)} className="p-3 bg-white dark:bg-slate-800 text-slate-400 hover:text-red-500 rounded-2xl shadow-sm transition-all hover:scale-110 active:scale-95">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" /></svg>
              </button>
            </div>

            <div className="flex-1 p-12 overflow-y-auto custom-scrollbar bg-slate-50 dark:bg-slate-950/50">
              <div id="printable-area" className="bg-white dark:bg-slate-900 min-h-full p-16 shadow-2xl rounded-2xl border border-slate-100 dark:border-slate-800 mx-auto max-w-[210mm]">
                {/* Header Document */}
                <div className="flex justify-between items-start mb-16">
                  <div className="space-y-1">
                    <p className="font-black text-xs uppercase tracking-tighter text-slate-800 dark:text-white">{template.coQuan}</p>
                    <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest leading-none border-t-2 border-slate-100 dark:border-slate-800 pt-1">Cơ quan thụ lý</p>
                  </div>
                  <div className="text-right space-y-1">
                    <p className="font-black text-xs uppercase text-slate-800 dark:text-white">CỘNG HÒA XÃ HỘI CHỦ NGHĨA VIỆT NAM</p>
                    <p className="text-[10px] font-bold text-slate-400">Độc lập - Tự do - Hạnh phúc</p>
                    <div className="w-32 h-0.5 bg-slate-100 dark:bg-slate-800 ml-auto mt-2"></div>
                  </div>
                </div>

                <div className="text-center mb-16">
                  <h2 className="text-3xl font-black text-slate-900 dark:text-white uppercase tracking-tighter mb-2">{template.tenMau}</h2>
                  <p className="text-xs text-slate-400 font-medium italic">Ngày khởi tạo: {new Date(job.ngayTao).toLocaleDateString('vi-VN')}</p>
                </div>

                <div className="space-y-8">
                  {template.fields.map(field => (
                    <div key={field.key} className="border-b border-slate-50 dark:border-slate-800 pb-4">
                      <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">{field.label}</p>
                      <p className="text-base font-bold text-slate-800 dark:text-slate-200 min-h-[1.5rem]">
                        {job.formData[field.key] || <span className="text-slate-200 dark:text-slate-800 italic">......................................................................................................</span>}
                      </p>
                    </div>
                  ))}
                </div>

                <div className="mt-24 grid grid-cols-2 gap-12 text-center">
                  <div></div>
                  <div className="space-y-16">
                    <div>
                      <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Người đại diện tập thể / cá nhân</p>
                      <p className="text-xs font-black text-slate-800 dark:text-white uppercase">(Ký và ghi rõ họ tên)</p>
                    </div>
                    <div className="pt-8 flex justify-center">
                      <div className="w-40 h-20 border-2 border-dashed border-slate-100 dark:border-slate-800 rounded-xl flex items-center justify-center">
                        <span className="text-[10px] text-slate-300 dark:text-slate-700 uppercase font-bold">Dán tem / Xác nhận</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="p-8 bg-white dark:bg-slate-900 border-t border-slate-100 dark:border-slate-800 flex justify-end space-x-4">
              <button onClick={() => setShowPrintModal(false)} className="px-8 py-4 text-slate-500 hover:text-slate-800 dark:hover:text-white font-black text-xs uppercase tracking-widest transition-all">Đóng thoát</button>
              {job.trangThai === TrangThaiHoSo.SAN_SANG_IN && (
                <button
                  onClick={async () => {
                    await handleSave(TrangThaiHoSo.DA_IN);
                    setTimeout(() => window.print(), 300);
                  }}
                  className="px-10 py-4 bg-purple-600 text-white font-black text-xs rounded-2xl shadow-xl shadow-purple-500/20 hover:bg-purple-700 hover:scale-105 active:scale-95 transition-all uppercase tracking-widest flex items-center"
                >
                  <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" /></svg>
                  Đánh dấu đã in & In
                </button>
              )}
              <button
                onClick={() => window.print()}
                className="px-10 py-4 bg-blue-600 text-white font-black text-xs rounded-2xl shadow-xl shadow-blue-500/20 hover:bg-blue-700 hover:scale-105 active:scale-95 transition-all uppercase tracking-widest flex items-center"
              >
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" /></svg>
                In bản cứng
              </button>
            </div>
          </div>
        </div>
      )}

      {selectedFile && (
        <div className="fixed inset-0 bg-slate-900/90 backdrop-blur-xl z-[60] flex items-center justify-center p-4 md:p-12 animate-in fade-in zoom-in duration-300">
          <div className="bg-white dark:bg-slate-900 w-full max-w-5xl h-full max-h-[90vh] rounded-[3rem] shadow-2xl flex flex-col overflow-hidden border border-white/10">
            <div className="p-6 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/30">
              <div className="flex items-center space-x-4">
                <div className="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-xl flex items-center justify-center text-blue-600">
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>
                </div>
                <div>
                  <h3 className="text-xl font-black text-slate-800 dark:text-white tracking-tighter">Xem trước tệp tin</h3>
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mt-0.5">{selectedFile.name}</p>
                </div>
              </div>
              <div className="flex items-center space-x-3">
                <a
                  href={selectedFile.path}
                  download={selectedFile.name}
                  className="p-3 bg-blue-600 text-white rounded-2xl shadow-lg shadow-blue-500/20 transition-all hover:scale-110 active:scale-95 flex items-center space-x-2"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a2 2 0 002 2h12a2 2 0 002-2v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg>
                </a>
                <button
                  onClick={() => setSelectedFile(null)}
                  className="p-3 bg-white dark:bg-slate-800 text-slate-400 hover:text-red-500 rounded-2xl shadow-sm transition-all hover:scale-110 active:scale-95"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" /></svg>
                </button>
              </div>
            </div>

            <div className="flex-1 bg-slate-100 dark:bg-slate-950 overflow-auto p-8 flex items-center justify-center">
              {selectedFile.path.startsWith('data:image/') ? (
                <img
                  src={selectedFile.path}
                  alt={selectedFile.name}
                  className="max-w-full max-h-full object-contain shadow-2xl rounded-lg"
                />
              ) : (selectedFile.path.startsWith('data:application/pdf') ||
                selectedFile.path.startsWith('data:application/x-pdf') ||
                selectedFile.name.toLowerCase().endsWith('.pdf')) ? (
                <embed
                  src={selectedFile.path}
                  type="application/pdf"
                  className="w-full h-full rounded-xl border-0 shadow-2xl"
                />
              ) : (
                <div className="text-center p-20 bg-white dark:bg-slate-900 rounded-[3rem] shadow-xl border border-slate-100 dark:border-slate-800">
                  <div className="text-6xl mb-6">📄</div>
                  <h4 className="text-lg font-black text-slate-800 dark:text-white uppercase tracking-tighter mb-2">Định dạng không hỗ trợ xem trực tiếp</h4>
                  <p className="text-slate-400 font-bold text-xs mb-8">Bạn có thể tải tệp xuống để xem trên thiết bị của mình.</p>
                  <a
                    href={selectedFile.path}
                    download={selectedFile.name}
                    className="inline-flex items-center px-8 py-4 bg-blue-600 text-white font-black text-xs rounded-2xl shadow-xl shadow-blue-500/20 hover:bg-blue-700 transition-all uppercase tracking-widest"
                  >
                    Tải tệp xuống ngay
                  </a>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>

  );
};

export default JobDetail;
