
import React, { useEffect, useState } from 'react';
import { ApiService } from '../api';
import { MauHoSo, TruongDuLieu, LoaiDuLieu } from '../types';

const TemplatePage: React.FC = () => {
  const [templates, setTemplates] = useState<MauHoSo[]>([]);
  const [editing, setEditing] = useState<MauHoSo | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    refreshTemplates();
  }, []);

  const refreshTemplates = async () => {
    setLoading(true);
    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ơ: ' + (error.message || 'Lỗi không xác định'));
    } finally {
      setLoading(false);
    }
  };

  const startNew = () => {
    setEditing({
      id: '',
      tenMau: '',
      coQuan: '',
      fields: [{ key: 'FIELD_1', label: 'Tên trường mới', type: LoaiDuLieu.VAN_BAN, required: true }]
    });
  };

  const handleDuplicate = (t: MauHoSo) => {
    setEditing({
      ...t,
      id: '',
      tenMau: `${t.tenMau} (Bản sao)`,
    });
  };

  const handleDelete = async (id: string) => {
    if (window.confirm('Bạn có chắc chắn muốn xóa mẫu hồ sơ này? Các hồ sơ đã tạo từ mẫu này có thể bị ảnh hưởng hiển thị.')) {
      try {
        await ApiService.deleteTemplate(id);
        refreshTemplates();
      } catch (error: any) {
        alert('Lỗi xóa mẫu hồ sơ: ' + (error.message || 'Không thể xóa mẫu hồ sơ'));
      }
    }
  };

  const addField = () => {
    if (!editing) return;
    setEditing({
      ...editing,
      fields: [...editing.fields, { key: `KEY_${Date.now()}`, label: 'Trường mới', type: LoaiDuLieu.VAN_BAN, required: false }]
    });
  };

  const removeField = (idx: number) => {
    if (!editing) return;
    const fs = [...editing.fields];
    fs.splice(idx, 1);
    setEditing({ ...editing, fields: fs });
  };

  const updateField = (idx: number, updates: Partial<TruongDuLieu>) => {
    if (!editing) return;
    const fs = [...editing.fields];
    fs[idx] = { ...fs[idx], ...updates };
    setEditing({ ...editing, fields: fs });
  };

  const save = async () => {
    if (!editing || !editing.tenMau || !editing.coQuan) {
      return alert('Vui lòng điền đủ tên mẫu và cơ quan chủ quản!');
    }
    
    if (editing.tenMau.trim().length < 3) {
      return alert('Tên mẫu phải có ít nhất 3 ký tự!');
    }
    
    if (editing.coQuan.trim().length < 3) {
      return alert('Tên cơ quan phải có ít nhất 3 ký tự!');
    }
    
    if (editing.fields.length === 0) {
      return alert('Mẫu hồ sơ phải có ít nhất 1 trường dữ liệu!');
    }
    
    // Kiểm tra trùng mã trường
    const keys = editing.fields.map(f => f.key);
    if (new Set(keys).size !== keys.length) {
      return alert('Lỗi: Có các trường dữ liệu bị trùng mã (Unique Key). Vui lòng kiểm tra lại!');
    }
    
    // Kiểm tra key và label không rỗng
    const invalidFields = editing.fields.filter(f => !f.key.trim() || !f.label.trim());
    if (invalidFields.length > 0) {
      return alert('Tất cả các trường dữ liệu phải có mã (Key) và nhãn (Label) hợp lệ!');
    }

    try {
      await ApiService.saveTemplate(editing);
      await refreshTemplates();
      setEditing(null);
    } catch (err: any) {
      alert('Đã có lỗi xảy ra khi lưu mẫu: ' + (err.message || 'Lỗi không xác định'));
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-800 dark:text-white">Quản lý Mẫu Hồ sơ</h2>
          <p className="text-sm text-gray-500 dark:text-slate-400 mt-1">Cấu hình biểu mẫu và các trường dữ liệu cho hệ thống OCR.</p>
        </div>
        <button
          onClick={startNew}
          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 Mẫu mới
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {loading ? (
          Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="h-48 bg-white dark:bg-slate-800 rounded-2xl animate-pulse border border-gray-100 dark:border-slate-700"></div>
          ))
        ) : (
          templates.map(t => (
            <div key={t.id} className="bg-white dark:bg-slate-800 p-6 rounded-2xl shadow-sm border border-gray-100 dark:border-slate-700 hover:shadow-xl hover:-translate-y-1 transition-all group flex flex-col">
              <div className="flex justify-between items-start mb-4">
                <div className="w-12 h-12 bg-blue-50 dark:bg-blue-900/30 rounded-xl flex items-center justify-center transition-colors">
                   <svg className="w-7 h-7 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                </div>
                <div className="flex space-x-1">
                  <button 
                    onClick={() => handleDuplicate(t)}
                    className="p-2 text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-all"
                    title="Sao chép mẫu"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" /></svg>
                  </button>
                  <button 
                    onClick={() => handleDelete(t.id)}
                    className="p-2 text-slate-400 hover:text-red-500 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-all"
                    title="Xóa mẫu"
                  >
                    <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>
              </div>
              
              <h4 className="font-bold text-gray-800 dark:text-slate-100 mb-1 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors line-clamp-2 min-h-[3rem]">{t.tenMau}</h4>
              <p className="text-[10px] text-gray-400 dark:text-slate-500 mb-6 uppercase tracking-widest font-bold">{t.coQuan}</p>
              
              <div className="mt-auto flex justify-between items-center pt-4 border-t border-gray-100 dark:border-slate-700">
                <div className="flex -space-x-2">
                   <span className="bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-slate-300 text-[10px] font-bold px-2.5 py-1 rounded-full border border-white dark:border-slate-800">
                     {t.fields.length} TRƯỜNG
                   </span>
                </div>
                <button 
                  onClick={() => setEditing(t)}
                  className="bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 font-bold text-xs py-2 px-4 rounded-lg hover:bg-blue-600 hover:text-white transition-all"
                >
                  Chỉnh sửa
                </button>
              </div>
            </div>
          ))
        )}
      </div>

      {editing && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-md flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-slate-800 rounded-3xl shadow-2xl w-full max-w-5xl max-h-[95vh] overflow-hidden flex flex-col border border-transparent dark:border-slate-700 animate-in fade-in zoom-in duration-300">
            <div className="p-6 border-b border-gray-100 dark:border-slate-700 flex justify-between items-center bg-gray-50 dark:bg-slate-900/50">
               <div className="flex items-center space-x-3">
                 <div className="w-10 h-10 bg-blue-600 rounded-xl flex items-center justify-center text-white shadow-lg">
                   <svg className="w-6 h-6" 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>
                 </div>
                 <div>
                   <h3 className="text-xl font-bold text-gray-800 dark:text-white">Thiết kế Biểu mẫu</h3>
                   <p className="text-[10px] text-gray-400 dark:text-slate-500 uppercase font-bold tracking-widest">Cấu hình tham số OCR & In ấn</p>
                 </div>
               </div>
               <button onClick={() => setEditing(null)} className="p-2 text-gray-400 hover:text-red-500 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-full transition-all">
                  <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 overflow-y-auto p-8 space-y-10 custom-scrollbar">
              <section className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div className="space-y-4">
                  <h5 className="text-xs font-bold text-blue-600 dark:text-blue-400 uppercase tracking-widest">Thông tin cơ bản</h5>
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-bold text-gray-700 dark:text-slate-300 mb-2">Tên mẫu hồ sơ</label>
                      <input
                        className="w-full px-4 py-3 rounded-xl border border-gray-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-gray-800 dark:text-white focus:ring-2 focus:ring-blue-500/20 outline-none transition-all shadow-sm"
                        value={editing.tenMau}
                        onChange={e => setEditing({ ...editing, tenMau: e.target.value })}
                        placeholder="VD: Đăng ký thành lập mới..."
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-bold text-gray-700 dark:text-slate-300 mb-2">Cơ quan chủ quản</label>
                      <input
                        className="w-full px-4 py-3 rounded-xl border border-gray-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-gray-800 dark:text-white focus:ring-2 focus:ring-blue-500/20 outline-none transition-all shadow-sm"
                        value={editing.coQuan}
                        onChange={e => setEditing({ ...editing, coQuan: e.target.value })}
                        placeholder="VD: Sở Kế hoạch và Đầu tư"
                      />
                    </div>
                  </div>
                </div>
                
                <div className="bg-blue-50 dark:bg-blue-900/10 p-6 rounded-2xl border border-blue-100 dark:border-blue-900/30">
                  <h5 className="text-xs font-bold text-blue-700 dark:text-blue-300 uppercase tracking-widest mb-4">Hướng dẫn thiết lập</h5>
                  <ul className="text-xs text-blue-600 dark:text-blue-400 space-y-3 list-disc pl-4 leading-relaxed">
                    <li><b>Unique Key:</b> Phải là duy nhất, không có khoảng trắng (Dùng để ánh xạ dữ liệu AI).</li>
                    <li><b>Loại dữ liệu:</b> Chọn đúng kiểu để hệ thống OCR tối ưu hóa kết quả nhận diện.</li>
                    <li><b>Required:</b> Đánh dấu nếu trường này bắt buộc phải có để hồ sơ hợp lệ.</li>
                  </ul>
                </div>
              </section>

              <section className="space-y-6">
                <div className="flex justify-between items-center border-b border-gray-100 dark:border-slate-700 pb-4">
                  <h5 className="text-xs font-bold text-blue-600 dark:text-blue-400 uppercase tracking-widest">Cấu trúc trường dữ liệu</h5>
                  <button onClick={addField} className="bg-blue-600 hover:bg-blue-700 text-white text-[10px] font-bold px-4 py-2 rounded-lg transition-all shadow-md active:scale-95">
                    + THÊM TRƯỜNG DỮ LIỆU
                  </button>
                </div>
                
                <div className="space-y-4">
                   {editing.fields.map((f, idx) => (
                     <div key={idx} className="bg-white dark:bg-slate-800/40 p-6 rounded-2xl border border-gray-100 dark:border-slate-700 shadow-sm transition-all hover:border-blue-200 dark:hover:border-slate-600 relative group/field">
                        <div className="grid grid-cols-1 md:grid-cols-12 gap-6 items-start">
                          <div className="md:col-span-4">
                            <label className="block text-[10px] uppercase font-bold text-gray-400 dark:text-slate-500 mb-1.5">Tên nhãn (Label)</label>
                            <input
                              className="w-full px-3 py-2.5 rounded-xl border border-gray-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-sm dark:text-white outline-none focus:ring-2 focus:ring-blue-500/10 transition-all"
                              value={f.label}
                              onChange={e => updateField(idx, { label: e.target.value })}
                            />
                          </div>
                          <div className="md:col-span-3">
                            <label className="block text-[10px] uppercase font-bold text-gray-400 dark:text-slate-500 mb-1.5">Mã trường (Unique Key)</label>
                            <input
                              className="w-full px-3 py-2.5 rounded-xl border border-gray-200 dark:border-slate-600 bg-gray-50 dark:bg-slate-900/50 text-xs font-mono dark:text-blue-400 outline-none focus:ring-2 focus:ring-blue-500/10 transition-all"
                              value={f.key}
                              onChange={e => updateField(idx, { key: e.target.value.toUpperCase().replace(/\s+/g, '_') })}
                            />
                          </div>
                          <div className="md:col-span-3">
                            <label className="block text-[10px] uppercase font-bold text-gray-400 dark:text-slate-500 mb-1.5">Kiểu dữ liệu</label>
                            <select 
                              className="w-full px-3 py-2.5 rounded-xl border border-gray-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-sm dark:text-white outline-none cursor-pointer"
                              value={f.type}
                              onChange={e => updateField(idx, { type: e.target.value as LoaiDuLieu })}
                            >
                              <option value={LoaiDuLieu.VAN_BAN}>Văn bản ngắn</option>
                              <option value={LoaiDuLieu.SO}>Con số</option>
                              <option value={LoaiDuLieu.NGAY}>Ngày tháng</option>
                              <option value={LoaiDuLieu.VUNG_VAN_BAN}>Đoạn văn dài</option>
                              {/* // Corrected LoaiDuLieu.DANH_SACH to LoaiDuLieu.DAN_SACH */}
                              <option value={LoaiDuLieu.DAN_SACH}>Danh sách chọn (Select)</option>
                            </select>
                          </div>
                          <div className="md:col-span-1 flex flex-col items-center">
                             <label className="text-[10px] uppercase font-bold text-gray-400 dark:text-slate-500 mb-3">Bắt buộc</label>
                             <input 
                               type="checkbox" 
                               className="w-6 h-6 rounded-lg text-blue-600 focus:ring-blue-500 dark:bg-slate-700 dark:border-slate-600 cursor-pointer"
                               checked={f.required} 
                               onChange={e => updateField(idx, { required: e.target.checked })} 
                             />
                          </div>
                          <div className="md:col-span-1 text-right flex items-center justify-end h-full">
                            <button onClick={() => removeField(idx)} className="p-3 text-red-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-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="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>
                        
                        {/* Cấu hình thêm cho Select Type */}
                        {/* // Corrected LoaiDuLieu.DANH_SACH to LoaiDuLieu.DAN_SACH */}
                        {f.type === LoaiDuLieu.DAN_SACH && (
                          <div className="mt-4 pt-4 border-t border-gray-50 dark:border-slate-700 animate-in slide-in-from-top-2 duration-200">
                             <label className="block text-[10px] uppercase font-bold text-blue-500 mb-1.5">Các tùy chọn (cách nhau bởi dấu phẩy)</label>
                             <input
                               className="w-full px-3 py-2 rounded-xl border border-blue-100 dark:border-blue-900/30 bg-blue-50/30 dark:bg-blue-900/10 text-xs dark:text-white outline-none"
                               placeholder="VD: Doanh nghiệp trong nước, Doanh nghiệp FDI, Hợp tác xã..."
                               value={f.options?.join(', ') || ''}
                               onChange={e => updateField(idx, { options: e.target.value.split(',').map(s => s.trim()).filter(s => s !== '') })}
                             />
                          </div>
                        )}
                     </div>
                   ))}
                </div>
              </section>
            </div>
            
            <div className="p-6 border-t border-gray-100 dark:border-slate-700 flex flex-col sm:flex-row space-y-3 sm:space-y-0 sm:space-x-4 bg-gray-50 dark:bg-slate-900/50">
              <button onClick={() => setEditing(null)} className="flex-1 py-4 text-gray-500 dark:text-slate-400 font-bold hover:bg-gray-200 dark:hover:bg-slate-700 rounded-2xl transition-all">Hủy bỏ</button>
              <button onClick={save} className="flex-[2] py-4 bg-blue-600 text-white font-bold rounded-2xl shadow-xl shadow-blue-500/20 hover:bg-blue-700 hover:-translate-y-0.5 transition-all active:scale-95">Lưu cấu hình mẫu hồ sơ</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default TemplatePage;
