'use client';
import { useState } from 'react';
import { useDocuments, Document, DocCategory } from '../../lib/documentStore';

const CATEGORY_ICONS: Record<DocCategory, string> = {
  Policy: 'ri-file-list-3-line',
  Certificate: 'ri-award-line',
  Evidence: 'ri-camera-line',
  Contract: 'ri-file-text-line',
  'Exit Interview': 'ri-door-open-line',
  Other: 'ri-attachment-line',
};

const CATEGORY_COLORS: Record<DocCategory, string> = {
  Policy: 'bg-blue-100 text-blue-700',
  Certificate: 'bg-amber-100 text-amber-700',
  Evidence: 'bg-red-100 text-red-700',
  Contract: 'bg-purple-100 text-purple-700',
  'Exit Interview': 'bg-teal-100 text-teal-700',
  Other: 'bg-gray-100 text-gray-600',
};

const STATUS_COLORS: Record<string, string> = {
  Active: 'bg-green-100 text-green-700',
  Expired: 'bg-red-100 text-red-700',
  'Expiring Soon': 'bg-amber-100 text-amber-700',
  Archived: 'bg-gray-100 text-gray-500',
};

const FILE_TYPE_ICONS: Record<string, string> = {
  PDF: 'ri-file-pdf-line',
  DOCX: 'ri-file-word-line',
  DOC: 'ri-file-word-line',
  XLSX: 'ri-file-excel-line',
  XLS: 'ri-file-excel-line',
  JPG: 'ri-image-line',
  PNG: 'ri-image-line',
};

const ALLOWED_TYPES = ['PDF', 'DOC', 'DOCX', 'XLS', 'XLSX', 'JPG', 'PNG'];

export default function DocumentsTab() {
  const { documents, addDocument, deleteDocument } = useDocuments();
  const [filterCat, setFilterCat] = useState('All');
  const [filterStatus, setFilterStatus] = useState('All');
  const [search, setSearch] = useState('');
  const [showUpload, setShowUpload] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
  const [form, setForm] = useState({
    name: '', category: 'Policy' as DocCategory, fileType: 'PDF', fileSize: '0 KB',
    linkedTo: '', linkedModule: '', expiryDate: '', confidential: false, description: '',
    uploadedBy: 'System Administrator',
  });

  const categories = ['All', 'Policy', 'Certificate', 'Evidence', 'Contract', 'Exit Interview', 'Other'];
  const statuses = ['All', 'Active', 'Expiring Soon', 'Expired', 'Archived'];

  const filtered = documents.filter(d => {
    const q = search.toLowerCase();
    const matchSearch = !q || d.name.toLowerCase().includes(q) || (d.linkedTo || '').toLowerCase().includes(q);
    const matchCat = filterCat === 'All' || d.category === filterCat;
    const matchStatus = filterStatus === 'All' || d.status === filterStatus;
    return matchSearch && matchCat && matchStatus;
  });

  const expiringCount = documents.filter(d => d.status === 'Expiring Soon').length;
  const expiredCount = documents.filter(d => d.status === 'Expired').length;

  const handleUpload = (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name.trim()) return;
    addDocument({ ...form });
    setShowUpload(false);
    setForm({ name: '', category: 'Policy', fileType: 'PDF', fileSize: '0 KB', linkedTo: '', linkedModule: '', expiryDate: '', confidential: false, description: '', uploadedBy: 'System Administrator' });
  };

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-4 gap-4">
        {[
          { label: 'Total Documents', value: documents.length, icon: 'ri-folder-3-line', color: 'text-gray-800', bg: 'bg-gray-50', iconColor: '#6b7280' },
          { label: 'Expiring Soon', value: expiringCount, icon: 'ri-alarm-warning-line', color: 'text-amber-700', bg: 'bg-amber-50', iconColor: '#d97706' },
          { label: 'Expired', value: expiredCount, icon: 'ri-error-warning-line', color: 'text-red-700', bg: 'bg-red-50', iconColor: '#dc2626' },
          { label: 'Confidential', value: documents.filter(d => d.confidential).length, icon: 'ri-lock-line', color: 'text-purple-700', bg: 'bg-purple-50', iconColor: '#7c3aed' },
        ].map(s => (
          <div key={s.label} className={`${s.bg} rounded-xl p-4 flex items-center gap-3`}>
            <div className="w-10 h-10 flex items-center justify-center rounded-xl bg-white shadow-sm">
              <i className={`${s.icon} text-xl`} style={{ color: s.iconColor }}></i>
            </div>
            <div>
              <p className="text-xs text-gray-500">{s.label}</p>
              <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
            </div>
          </div>
        ))}
      </div>

      {(expiringCount > 0 || expiredCount > 0) && (
        <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl flex items-center gap-3">
          <div className="w-8 h-8 flex items-center justify-center flex-shrink-0"><i className="ri-alarm-warning-line text-amber-600 text-xl"></i></div>
          <div>
            <p className="text-sm font-semibold text-amber-800">Document Expiry Alerts</p>
            <p className="text-xs text-amber-700">{expiringCount} document(s) expiring within 30 days. {expiredCount} document(s) already expired. Please review and renew.</p>
          </div>
        </div>
      )}

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="font-bold text-gray-800">Document Repository</h3>
            <p className="text-xs text-gray-500 mt-0.5">Supported: PDF, DOC, DOCX, XLS, XLSX, JPG, PNG • Max 10MB per file</p>
          </div>
          <button onClick={() => setShowUpload(true)} className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#b828a0' }}>
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-upload-2-line text-sm"></i></div>
            Upload Document
          </button>
        </div>

        <div className="flex items-center gap-3 mb-4">
          <input type="text" placeholder="Search documents..." value={search} onChange={e => setSearch(e.target.value)}
            className="flex-1 border border-gray-200 rounded-xl px-3 py-2 text-sm outline-none" />
          <div className="flex gap-2">
            {categories.map(c => (
              <button key={c} onClick={() => setFilterCat(c)}
                className={`px-3 py-2 rounded-xl text-xs font-medium cursor-pointer whitespace-nowrap transition-all ${filterCat === c ? 'text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
                style={filterCat === c ? { background: '#b828a0' } : {}}>
                {c}
              </button>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 gap-2">
          {filtered.map(doc => {
            const ftIcon = FILE_TYPE_ICONS[doc.fileType] || 'ri-file-line';
            return (
              <div key={doc.id} className="flex items-center gap-4 p-3.5 border border-gray-100 rounded-xl hover:bg-gray-50/50 transition-colors">
                <div className="w-10 h-10 flex items-center justify-center rounded-xl bg-pink-50 flex-shrink-0">
                  <i className={`${ftIcon} text-xl`} style={{ color: '#b828a0' }}></i>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-semibold text-gray-800 truncate">{doc.name}</p>
                    {doc.confidential && <div className="w-4 h-4 flex items-center justify-center flex-shrink-0"><i className="ri-lock-line text-xs text-red-500"></i></div>}
                  </div>
                  <div className="flex items-center gap-2 mt-0.5">
                    <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${CATEGORY_COLORS[doc.category]}`}>{doc.category}</span>
                    <span className="text-xs text-gray-400">{doc.fileType} • {doc.fileSize}</span>
                    {doc.linkedTo && <span className="text-xs text-gray-400">→ {doc.linkedTo}</span>}
                    <span className="text-xs text-gray-400">Uploaded {doc.uploadDate}</span>
                  </div>
                </div>
                <div className="flex items-center gap-3 flex-shrink-0">
                  {doc.expiryDate && (
                    <div className="text-right">
                      <p className="text-xs text-gray-400">Expires</p>
                      <p className="text-xs font-semibold text-gray-600">{doc.expiryDate}</p>
                    </div>
                  )}
                  <span className={`px-2.5 py-1 rounded-full text-xs font-medium ${STATUS_COLORS[doc.status]}`}>{doc.status}</span>
                  <button className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-blue-50 cursor-pointer text-blue-500" title="Download">
                    <i className="ri-download-line text-sm"></i>
                  </button>
                  <button onClick={() => setDeleteConfirm(doc.id)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-red-50 cursor-pointer text-red-400" title="Delete">
                    <i className="ri-delete-bin-line text-sm"></i>
                  </button>
                </div>
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div className="text-center py-10 text-gray-400 text-sm">No documents found matching your filters.</div>
          )}
        </div>
      </div>

      {showUpload && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
            <div className="p-5 border-b border-gray-100 flex items-center justify-between" style={{ background: 'linear-gradient(135deg, #b828a0 0%, #8a1e78 100%)' }}>
              <h3 className="text-white font-bold">Upload Document</h3>
              <button onClick={() => setShowUpload(false)} className="w-8 h-8 flex items-center justify-center text-white/80 hover:text-white cursor-pointer">
                <i className="ri-close-line text-xl"></i>
              </button>
            </div>
            <form onSubmit={handleUpload} className="p-5 space-y-4">
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Document Name *</label>
                <input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} required
                  className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" placeholder="e.g. Employee Contract - Jane Mwangi" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Category</label>
                  <div className="relative">
                    <select value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value as DocCategory }))}
                      className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 appearance-none">
                      {(['Policy', 'Certificate', 'Evidence', 'Contract', 'Exit Interview', 'Other'] as DocCategory[]).map(c => <option key={c}>{c}</option>)}
                    </select>
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">File Type</label>
                  <div className="relative">
                    <select value={form.fileType} onChange={e => setForm(f => ({ ...f, fileType: e.target.value }))}
                      className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 appearance-none">
                      {ALLOWED_TYPES.map(t => <option key={t}>{t}</option>)}
                    </select>
                  </div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Linked To (Employee/Case ID)</label>
                  <input value={form.linkedTo} onChange={e => setForm(f => ({ ...f, linkedTo: e.target.value }))}
                    className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" placeholder="e.g. UF001" />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Expiry Date (if applicable)</label>
                  <input type="date" value={form.expiryDate} onChange={e => setForm(f => ({ ...f, expiryDate: e.target.value }))}
                    className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none" />
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Description</label>
                <textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} rows={2} maxLength={500}
                  className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none resize-none" placeholder="Brief description..." />
              </div>
              <div className="flex items-center gap-2 p-3 bg-amber-50 border border-amber-100 rounded-xl">
                <input type="checkbox" id="conf" checked={form.confidential} onChange={e => setForm(f => ({ ...f, confidential: e.target.checked }))} className="cursor-pointer" />
                <label htmlFor="conf" className="text-sm text-amber-800 font-medium cursor-pointer">Mark as Confidential (restricted access)</label>
              </div>
              <div className="border-2 border-dashed border-gray-200 rounded-xl p-6 text-center">
                <div className="w-10 h-10 flex items-center justify-center mx-auto mb-2"><i className="ri-upload-cloud-2-line text-3xl text-gray-400"></i></div>
                <p className="text-sm text-gray-500">File upload simulation — select file type above</p>
                <p className="text-xs text-gray-400 mt-1">Max 10MB per file</p>
              </div>
              <div className="flex gap-3 pt-2">
                <button type="button" onClick={() => setShowUpload(false)} className="flex-1 py-2.5 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 cursor-pointer">Cancel</button>
                <button type="submit" className="flex-1 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer" style={{ background: '#b828a0' }}>Upload Document</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {deleteConfirm && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl p-6 max-w-sm w-full text-center shadow-2xl">
            <div className="w-14 h-14 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <i className="ri-delete-bin-line text-2xl text-red-500"></i>
            </div>
            <h3 className="font-bold text-gray-800 mb-2">Delete Document?</h3>
            <p className="text-sm text-gray-500 mb-5">This action cannot be undone. The document will be permanently removed.</p>
            <div className="flex gap-3">
              <button onClick={() => setDeleteConfirm(null)} className="flex-1 py-2.5 rounded-xl border border-gray-200 text-sm font-medium cursor-pointer">Cancel</button>
              <button onClick={() => { deleteDocument(deleteConfirm); setDeleteConfirm(null); }}
                className="flex-1 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer bg-red-500">Delete</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
