'use client';
import { useState } from 'react';
import { trainingRecords, TrainingRecord, CertStatus } from './trainingModuleData';
import { triggerFileDownload } from '../../../lib/autoDownloadPdf';

const CERT_STATUS_COLORS: Record<CertStatus, string> = {
  Submitted: 'bg-green-100 text-green-700',
  Pending: 'bg-yellow-100 text-yellow-700',
  Missing: 'bg-red-100 text-red-700',
};

function ExpiryBadge({ days }: { days?: number }) {
  if (days === undefined) return <span className="text-xs text-gray-400">No expiry</span>;
  if (days <= 7) return <span className="px-2 py-0.5 rounded-full text-xs font-bold bg-red-100 text-red-700">Expires in {days}d</span>;
  if (days <= 30) return <span className="px-2 py-0.5 rounded-full text-xs font-semibold bg-orange-100 text-orange-700">Expires in {days}d</span>;
  return <span className="px-2 py-0.5 rounded-full text-xs text-gray-500 bg-gray-100">{days}d remaining</span>;
}

export default function TrainingRecordsTab() {
  const [records, setRecords] = useState<TrainingRecord[]>(trainingRecords);
  const [search, setSearch] = useState('');
  const [filterDept, setFilterDept] = useState('All');
  const [filterCert, setFilterCert] = useState('All');
  const [uploadModal, setUploadModal] = useState<TrainingRecord | null>(null);
  const [uploadForm, setUploadForm] = useState({ issueDate: '', expiryDate: '' });
  const [reminderToast, setReminderToast] = useState('');

  const showToast = (msg: string) => { setReminderToast(msg); setTimeout(() => setReminderToast(''), 3000); };

  const depts = ['All', ...Array.from(new Set(records.map(r => r.dept)))];

  const filtered = records.filter(r =>
    (filterDept === 'All' || r.dept === filterDept) &&
    (filterCert === 'All' || r.certStatus === filterCert) &&
    (r.employeeName.toLowerCase().includes(search.toLowerCase()) ||
      r.courseName.toLowerCase().includes(search.toLowerCase()))
  );

  const submitted = records.filter(r => r.certStatus === 'Submitted').length;
  const pending = records.filter(r => r.certStatus === 'Pending').length;
  const missing = records.filter(r => r.certStatus === 'Missing').length;
  const expiringSoon = records.filter(r => r.daysToExpiry !== undefined && r.daysToExpiry <= 30).length;

  const handleUpload = () => {
    if (!uploadModal) return;
    setRecords(prev => prev.map(r => r.id === uploadModal.id
      ? {
        ...r,
        certStatus: 'Submitted' as CertStatus,
        certUploadDate: new Date().toISOString().split('T')[0],
        expiryDate: uploadForm.expiryDate || r.expiryDate,
      }
      : r
    ));
    showToast(`Certificate uploaded for ${uploadModal.employeeName}`);
    setUploadModal(null);
    setUploadForm({ issueDate: '', expiryDate: '' });
  };

  const handleReminder = (r: TrainingRecord) => {
    showToast(`Reminder sent to ${r.employeeName} to upload certificate for "${r.courseName}"`);
  };

  return (
    <div className="space-y-5">
      {reminderToast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg text-sm font-medium">{reminderToast}</div>
      )}

      {(missing > 0 || expiringSoon > 0) && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4">
          <div className="flex items-center gap-2 mb-2">
            <div className="w-5 h-5 flex items-center justify-center">
              <i className="ri-alarm-warning-line text-red-600"></i>
            </div>
            <h4 className="text-sm font-bold text-red-700">Certificate Alerts</h4>
          </div>
          <div className="flex flex-wrap gap-3">
            {missing > 0 && (
              <span className="px-3 py-1.5 bg-red-100 border border-red-200 rounded-lg text-xs font-semibold text-red-700">
                {missing} certificate(s) missing (&gt;7 days)
              </span>
            )}
            {expiringSoon > 0 && (
              <span className="px-3 py-1.5 bg-orange-100 border border-orange-200 rounded-lg text-xs font-semibold text-orange-700">
                {expiringSoon} certificate(s) expiring within 30 days
              </span>
            )}
          </div>
        </div>
      )}

      <div className="grid grid-cols-4 gap-4">
        {[
          { label: 'Total Records', value: records.length, icon: 'ri-history-line', color: 'text-blue-600 bg-blue-50' },
          { label: 'Certificates Submitted', value: submitted, icon: 'ri-award-line', color: 'text-green-600 bg-green-50' },
          { label: 'Pending Upload', value: pending, icon: 'ri-time-line', color: 'text-yellow-600 bg-yellow-50' },
          { label: 'Missing (>7 days)', value: missing, icon: 'ri-close-circle-line', color: 'text-red-600 bg-red-50' },
        ].map(({ label, value, icon, color }) => (
          <div key={label} className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
            <div className={`w-10 h-10 rounded-xl ${color} flex items-center justify-center mb-3`}>
              <i className={`${icon} text-lg`}></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{value}</p>
            <p className="text-sm text-gray-500 mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-100">
        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between flex-wrap gap-3">
          <div className="flex items-center gap-2 flex-wrap">
            {depts.map(d => (
              <button key={d} onClick={() => setFilterDept(d)}
                className="px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap transition-all"
                style={filterDept === d ? { background: '#b22698', color: 'white' } : { background: '#f3f4f6', color: '#6b7280' }}>
                {d}
              </button>
            ))}
            <div className="w-px h-4 bg-gray-200"></div>
            {(['All', 'Submitted', 'Pending', 'Missing'] as const).map(s => (
              <button key={s} onClick={() => setFilterCert(s)}
                className="px-3 py-1.5 rounded-full text-xs font-medium cursor-pointer whitespace-nowrap transition-all"
                style={filterCert === s ? { background: '#374151', color: 'white' } : { background: '#f3f4f6', color: '#6b7280' }}>
                {s}
              </button>
            ))}
          </div>
          <div className="relative">
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search records..."
              className="bg-gray-50 border border-gray-200 rounded-lg px-4 py-1.5 text-sm w-44 outline-none" />
            <div className="w-4 h-4 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2">
              <i className="ri-search-line text-gray-400 text-sm"></i>
            </div>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-100">
                {['Employee', 'Department', 'Course', 'Completion Date', 'Certificate Status', 'Certificate', 'Expiry Date'].map(h => (
                  <th key={h} className="text-left text-xs font-semibold text-gray-500 px-4 py-3 whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(r => {
                const isMissing = r.certStatus === 'Missing';
                const isExpiring = r.daysToExpiry !== undefined && r.daysToExpiry <= 30;
                return (
                  <tr key={r.id} className={`border-b border-gray-50 hover:bg-gray-50 transition-colors ${isMissing && r.daysSinceCompletion > 7 ? 'bg-red-50/40' : isExpiring ? 'bg-orange-50/30' : ''}`}>
                    <td className="px-4 py-3">
                      <p className="text-sm font-medium text-gray-800">{r.employeeName}</p>
                      <p className="text-xs text-gray-400">{r.employeeId}</p>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-600">{r.dept}</td>
                    <td className="px-4 py-3 text-sm text-gray-700 max-w-[180px]">
                      <p className="truncate">{r.courseName}</p>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-600">{r.completionDate}</td>
                    <td className="px-4 py-3">
                      <span className={`px-2.5 py-1 rounded-full text-xs font-semibold ${CERT_STATUS_COLORS[r.certStatus]}`}>
                        {r.certStatus}
                      </span>
                      {r.certStatus === 'Missing' && r.daysSinceCompletion > 7 && (
                        <p className="text-xs text-red-500 mt-0.5">{r.daysSinceCompletion}d since completion</p>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      {r.certStatus === 'Submitted' ? (
                        <button
                          onClick={() => {
                            const UWEZO_LOGO = 'https://storage.readdy-site.link/project_files/8353c6c3-4df0-48e3-b13e-2f6c24e6f89d/6d094512-dcbf-4464-ad6a-2cd0e9a78386_uwezo-fund-logo.png?v=507c066dfae2633b1a8385356d2c557b';
                            const today = new Date().toLocaleDateString('en-KE', { year: 'numeric', month: 'long', day: 'numeric' });
                            const style = 'body{font-family:Tahoma,Arial,sans-serif;font-size:11pt;color:#222;background:#fff;margin:0;padding:30px;}' +
                              '.page{max-width:700px;margin:0 auto;border:2px solid #b22698;padding:40px;border-radius:8px;}' +
                              '.logo{text-align:center;margin-bottom:20px;}' +
                              '.logo img{height:70px;}' +
                              '.title{text-align:center;font-size:20pt;font-weight:bold;color:#b22698;margin:10px 0;letter-spacing:2px;font-family:Arial Black,Impact,sans-serif;}' +
                              '.subtitle{text-align:center;font-size:12pt;color:#555;margin-bottom:30px;}' +
                              '.cert-text{text-align:center;font-size:13pt;margin:20px 0;line-height:1.8;}' +
                              '.name{font-size:18pt;font-weight:bold;color:#222;border-bottom:2px solid #b22698;display:inline-block;padding:0 20px;margin:10px 0;}' +
                              '.details{margin:20px 0;border-top:1px solid #eee;padding-top:20px;}' +
                              '.detail-row{display:flex;justify-content:space-between;padding:6px 0;font-size:11pt;border-bottom:1px solid #f5f5f5;}' +
                              '.footer{text-align:center;margin-top:30px;font-size:9pt;color:#888;border-top:1px solid #eee;padding-top:15px;}';
                            const html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Training Certificate</title><style>' + style + '</style></head><body><div class="page"><div class="logo"><img src="' + UWEZO_LOGO + '" alt="Uwezo Fund" /></div><div class="title">UWEZO FUND OVERSIGHT BOARD</div><div class="subtitle">CERTIFICATE OF TRAINING COMPLETION</div><div class="cert-text">This is to certify that<br/><span class="name">' + r.employeeName + '</span><br/>has successfully completed the training program</div><div class="cert-text" style="font-size:15pt;font-weight:bold;color:#b22698;">' + r.courseName + '</div><div class="details"><div class="detail-row"><span>Provider:</span><span>' + r.provider + '</span></div><div class="detail-row"><span>Department:</span><span>' + r.dept + '</span></div><div class="detail-row"><span>Completion Date:</span><span>' + r.completionDate + '</span></div><div class="detail-row"><span>Certificate Uploaded:</span><span>' + (r.certUploadDate || 'N/A') + '</span></div></div><div class="footer">Uwezo Fund HRMS &bull; Official Training Record &bull; ' + today + '</div></div></body></html>';
                            triggerFileDownload(html, 'Training_Certificate_' + r.employeeName.replace(/\s+/g, '_') + '.pdf');
                          }}
                          className="flex items-center gap-1 text-xs font-medium cursor-pointer whitespace-nowrap hover:opacity-80"
                          style={{ color: '#b22698' }}>
                          <i className="ri-download-line"></i> Download
                        </button>
                      ) : (
                        <span className="text-xs text-gray-400">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <ExpiryBadge days={r.daysToExpiry} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {filtered.length === 0 && (
            <div className="text-center py-10 text-gray-400 text-sm">No training records found</div>
          )}
        </div>
      </div>

      {uploadModal && (
        <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-md">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b22698' }}>
              <div>
                <h2 className="text-white font-bold text-lg">Upload Certificate (On Behalf)</h2>
                <p className="text-pink-200 text-sm">{uploadModal.employeeName}</p>
              </div>
              <button onClick={() => setUploadModal(null)} className="w-8 h-8 flex items-center justify-center cursor-pointer">
                <i className="ri-close-line text-white text-xl"></i>
              </button>
            </div>
            <div className="p-6 space-y-4">
              <div className="bg-gray-50 rounded-xl p-4">
                <p className="text-sm font-semibold text-gray-800">{uploadModal.courseName}</p>
                <p className="text-xs text-gray-500 mt-1">Completed: {uploadModal.completionDate}</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Certificate File (PDF/JPG/PNG)</label>
                <div className="border-2 border-dashed border-gray-200 rounded-xl p-6 text-center cursor-pointer hover:border-pink-300 transition-colors">
                  <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-300"></i>
                  </div>
                  <p className="text-sm text-gray-500">Click to upload or drag & drop</p>
                  <p className="text-xs text-gray-400 mt-1">PDF, JPG, PNG — max 10MB</p>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Issue Date</label>
                <input type="date" value={uploadForm.issueDate} onChange={e => setUploadForm(p => ({ ...p, issueDate: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-pink-400" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Expiry Date (optional)</label>
                <input type="date" value={uploadForm.expiryDate} onChange={e => setUploadForm(p => ({ ...p, expiryDate: e.target.value }))}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-pink-400" />
              </div>
              <div className="flex gap-3">
                <button onClick={handleUpload}
                  className="flex-1 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer hover:opacity-90"
                  style={{ background: '#b22698' }}>
                  Upload Certificate
                </button>
                <button onClick={() => setUploadModal(null)}
                  className="flex-1 py-2.5 rounded-xl border border-gray-200 text-gray-600 text-sm font-semibold cursor-pointer hover:bg-gray-50">
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
