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

const JobPage: React.FC = () => {
  const [jobs, setJobs] = useState<HoSo[]>([]);
  const [templates, setTemplates] = useState<MauHoSo[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [selectedTemplateId, setSelectedTemplateId] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('ALL');
  const navigate = useNavigate();

  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(() => {
    loadData();
    loadTemplates();
  }, []);

  const loadData = async () => {
    try {
      const data = await ApiService.getJobs();
      setJobs(data);
    } catch (error: any) {
      console.error('Error loading jobs:', error);
      alert('Không thể tải danh sách hồ sơ. Vui lòng thử lại.');
    }
  };

  const loadTemplates = async () => {
    try {
      const data = await ApiService.getTemplates();
      setTemplates(data);
    } catch (error: any) {
      console.error('Error loading templates:', error);
      alert('Không thể tải danh sách mẫu hồ sơ. Vui lòng thử lại.');
    }
  };

  const handleCreateJob = async () => {
    if (!selectedTemplateId) return alert('Vui lòng chọn một mẫu hồ sơ!');
    const template = templates.find(t => t.id === selectedTemplateId);
    if (!template) return;

    try {
      const newJob: HoSo = {
        id: '', // Backend will generate ID
        templateId: template.id,
        templateName: template.tenMau,
        coQuan: template.coQuan,
        trangThai: TrangThaiHoSo.BAN_NHAP,
        formData: {},
        confidence: {},
        files: [],
        nguoiTao: ApiService.currentUser?.fullName || 'Ẩn danh',
        ngayTao: new Date().toISOString(),
        ngayCapNhat: new Date().toISOString()
      };

      const savedJob = await ApiService.saveJob(newJob);
      ApiService.log('Tạo hồ sơ', `Tạo hồ sơ mới dựa trên mẫu: ${template.tenMau}`).catch(console.error);
      navigate(`/ho-so/${savedJob.id}`);
    } catch (error: any) {
      alert('Lỗi tạo hồ sơ: ' + (error.message || 'Không thể tạo hồ sơ mới'));
    }
  };

  const handleDelete = async (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    if (window.confirm('Bạn có chắc chắn muốn xóa hồ sơ này? Thao tác này không thể hoàn tác.')) {
      try {
        await ApiService.deleteJob(id);
        loadData();
      } catch (error: any) {
        alert('Lỗi xóa hồ sơ: ' + (error.message || 'Không thể xóa hồ sơ'));
      }
    }
  };

  const filteredJobs = jobs.filter(job => {
    const matchesSearch = 
      (job.formData.TEN_CONG_TY || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
      (job.formData.MA_SO_THUE || '').includes(searchTerm);
    const matchesStatus = statusFilter === 'ALL' || job.trangThai === statusFilter;
    return matchesSearch && matchesStatus;
  });

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-white">Danh sách Hồ sơ</h2>
        <button
          onClick={() => setShowModal(true)}
          className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2.5 px-6 rounded-xl shadow-lg flex items-center transition-all active:scale-95"
        >
          <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
          </svg>
          Tạo Hồ sơ mới
        </button>
      </div>

      {/* Bộ lọc & Tìm kiếm */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 bg-white/80 dark:bg-slate-800/80 backdrop-blur-xl p-4 rounded-2xl border border-gray-200/50 dark:border-slate-700/50 shadow-lg transition-all">
        <div className="relative md:col-span-2">
          <span className="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-400">
            <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
          </span>
          <input 
            type="text"
            className="block w-full pl-10 pr-3 py-2.5 border border-gray-200 dark:border-slate-600 rounded-xl bg-gray-50 dark:bg-slate-700 text-sm focus:ring-2 focus:ring-blue-100 dark:focus:ring-blue-900 transition-all outline-none dark:text-white"
            placeholder="Tìm theo tên công ty hoặc mã số thuế..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <select 
          className="block w-full px-3 py-2.5 border border-gray-200 dark:border-slate-600 rounded-xl bg-gray-50 dark:bg-slate-700 text-sm focus:ring-2 focus:ring-blue-100 transition-all outline-none dark:text-white"
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
        >
          <option value="ALL">Tất cả trạng thái</option>
          <option value={TrangThaiHoSo.BAN_NHAP}>Bản nháp</option>
          <option value={TrangThaiHoSo.SAN_SANG_IN}>Sẵn sàng in</option>
          <option value={TrangThaiHoSo.DA_IN}>Đã in</option>
          <option value={TrangThaiHoSo.LUU_TRU}>Lưu trữ</option>
        </select>
      </div>

      <div className="bg-white/80 dark:bg-slate-800/80 backdrop-blur-xl rounded-2xl shadow-lg border border-gray-200/50 dark:border-slate-700/50 overflow-hidden transition-all">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-gray-50 dark:bg-slate-700/50 border-b border-gray-100 dark:border-slate-700">
              <tr>
                <th className="px-6 py-4 text-xs font-bold text-gray-500 dark:text-slate-400 uppercase tracking-wider">Khách hàng / Doanh nghiệp</th>
                <th className="px-6 py-4 text-xs font-bold text-gray-500 dark:text-slate-400 uppercase tracking-wider">Mẫu & Cơ quan</th>
                <th className="px-6 py-4 text-xs font-bold text-gray-500 dark:text-slate-400 uppercase tracking-wider">Trạng thái</th>
                <th className="px-6 py-4 text-xs font-bold text-gray-500 dark:text-slate-400 uppercase tracking-wider">Cập nhật cuối</th>
                <th className="px-6 py-4 text-xs font-bold text-gray-500 dark:text-slate-400 uppercase tracking-wider text-right">Thao tác</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-slate-700">
              {filteredJobs.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-6 py-12 text-center text-gray-400 dark:text-slate-500 font-medium">Không tìm thấy hồ sơ nào phù hợp.</td>
                </tr>
              ) : (
                filteredJobs.map(job => (
                  <tr 
                    key={job.id} 
                    className="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition-colors group cursor-pointer"
                    onClick={() => navigate(`/ho-so/${job.id}`)}
                  >
                    <td className="px-6 py-4">
                      <p className="text-sm font-bold text-gray-800 dark:text-slate-200">{job.formData.TEN_CONG_TY || 'Chưa nhập tên'}</p>
                      <p className="text-xs text-gray-500 dark:text-slate-400 font-mono">MST: {job.formData.MA_SO_THUE || '--'}</p>
                    </td>
                    <td className="px-6 py-4 text-sm">
                      <p className="font-medium text-gray-700 dark:text-slate-300">{job.templateName}</p>
                      <p className="text-xs text-gray-400 dark:text-slate-500">{job.coQuan}</p>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`px-2.5 py-1 rounded-lg text-[10px] font-bold uppercase ${
                        job.trangThai === TrangThaiHoSo.SAN_SANG_IN ? 'bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-400' :
                        job.trangThai === TrangThaiHoSo.BAN_NHAP ? 'bg-yellow-100 dark:bg-yellow-900/40 text-yellow-700 dark:text-yellow-400' : 
                        job.trangThai === TrangThaiHoSo.DA_IN ? 'bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-400' :
                        job.trangThai === TrangThaiHoSo.LUU_TRU ? 'bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300' :
                        'bg-gray-100 dark:bg-slate-700 text-gray-700 dark:text-slate-300'
                      }`}>
                        {statusNames[job.trangThai] || job.trangThai.replace(/_/g, ' ')}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-500 dark:text-slate-400">
                      {new Date(job.ngayCapNhat).toLocaleDateString('vi-VN')}
                      <p className="text-[10px] opacity-60">{new Date(job.ngayCapNhat).toLocaleTimeString('vi-VN', {hour:'2-digit', minute:'2-digit'})}</p>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex justify-end space-x-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button 
                          className="p-2 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-all"
                          title="Chỉnh sửa"
                        >
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                        </button>
                        <button 
                          onClick={(e) => handleDelete(job.id, e)}
                          className="p-2 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-all"
                          title="Xóa hồ sơ"
                        >
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" 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>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal chọn mẫu */}
      {showModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-full max-w-lg p-8 animate-in fade-in zoom-in duration-200 border border-transparent dark:border-slate-700">
            <h3 className="text-xl font-bold text-gray-800 dark:text-white mb-6">Chọn Mẫu Hồ sơ</h3>
            <div className="space-y-4 max-h-96 overflow-y-auto pr-2 custom-scrollbar">
              {templates.map(t => (
                <label 
                  key={t.id} 
                  className={`flex items-start p-4 border rounded-xl cursor-pointer transition-all ${
                    selectedTemplateId === t.id 
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 shadow-sm' 
                      : 'border-gray-200 dark:border-slate-700 hover:border-blue-200 dark:hover:border-slate-600'
                  }`}
                >
                  <input
                    type="radio"
                    name="template"
                    className="mt-1 h-4 w-4 text-blue-600"
                    onChange={() => setSelectedTemplateId(t.id)}
                    checked={selectedTemplateId === t.id}
                  />
                  <div className="ml-3">
                    <p className="text-sm font-bold text-gray-800 dark:text-slate-200">{t.tenMau}</p>
                    <p className="text-xs text-gray-500 dark:text-slate-400">{t.coQuan}</p>
                  </div>
                </label>
              ))}
            </div>
            <div className="flex space-x-4 mt-8">
              <button
                onClick={() => setShowModal(false)}
                className="flex-1 py-3 px-4 rounded-xl text-gray-600 dark:text-slate-400 font-bold hover:bg-gray-100 dark:hover:bg-slate-700 transition-colors"
              >
                Hủy bỏ
              </button>
              <button
                onClick={handleCreateJob}
                className="flex-1 py-3 px-4 rounded-xl bg-blue-600 text-white font-bold shadow-lg hover:bg-blue-700 transition-all active:scale-95"
              >
                Bắt đầu xử lý
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default JobPage;
