'use client';
import { useState } from 'react';
import { useAuth } from '../../../lib/authContext';
import EmployeeLayout from '../../../components/EmployeeLayout';
import { disciplinaryCases, complaintTypes, departments, employees, DisciplinaryCase, ComplaintType } from '../../hr/disciplinary/disciplinaryData';

type Tab = 'report' | 'submissions' | 'history';

const SEVERITY_CONFIG = {
  High: { color: '#dc2626', bg: '#fee2e2' },
  Medium: { color: '#d97706', bg: '#fef3c7' },
  Low: { color: '#16a34a', bg: '#dcfce7' },
};

export default function EmployeeDisciplinaryPage() {
  const { user } = useAuth();

  if (!user) return null;

  const [activeTab, setActiveTab] = useState<Tab>('report');
  const [cases, setCases] = useState<DisciplinaryCase[]>(disciplinaryCases);
  const [toast, setToast] = useState('');
  const [form, setForm] = useState({
    employeeName: '',
    employeeId: '',
    department: '',
    complaintType: '' as ComplaintType | '',
    severity: 'Medium' as 'High' | 'Medium' | 'Low',
    incidentDate: '',
    description: '',
    witnesses: '',
    isConfidential: false,
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [viewCase, setViewCase] = useState<DisciplinaryCase | null>(null);

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3500); };

  const mySubmissions = cases.filter(c => c.createdBy === user.name);
  const caseHistory = cases.filter(c => c.employeeName === user.name || (user.name && c.witnesses?.includes(user.name)));

  const handleSubmit = () => {
    const newErrors: Record<string, string> = {};
    if (!form.employeeName) newErrors.employeeName = 'Required';
    if (!form.department) newErrors.department = 'Required';
    if (!form.complaintType) newErrors.complaintType = 'Required';
    if (!form.incidentDate) newErrors.incidentDate = 'Required';
    if (!form.description || form.description.length < 50) newErrors.description = 'Please provide at least 50 characters';
    if (Object.keys(newErrors).length > 0) { setErrors(newErrors); return; }

    const newCase: DisciplinaryCase = {
      id: String(cases.length + 1),
      caseNumber: `DC-2026-${String(cases.length + 1).padStart(3, '0')}`,
      employeeName: form.employeeName,
      employeeId: employees.find(e => e.name === form.employeeName)?.id || 'UF-XXXX',
      department: form.department,
      complaintType: form.complaintType as ComplaintType,
      severity: form.severity,
      incidentDate: form.incidentDate,
      description: form.description,
      witnesses: form.witnesses || undefined,
      evidenceFiles: [],
      isConfidential: form.isConfidential,
      createdBy: user.name || (user.email as string) || 'System',
      createdByRole: user.role === 'employee' ? 'Employee' : user.role.toUpperCase(),
      createdAt: new Date().toISOString(),
    };
    setCases(prev => [newCase, ...prev]);
    setForm({ employeeName: '', employeeId: '', department: '', complaintType: '', severity: 'Medium', incidentDate: '', description: '', witnesses: '', isConfidential: false });
    setErrors({});
    setActiveTab('submissions');
    showToast('Case reported successfully. HR has been notified.');
  };

  const TABS: { id: Tab; label: string; icon: string }[] = [
    { id: 'report', label: 'Report a Case', icon: 'ri-alarm-warning-line' },
    { id: 'submissions', label: 'My Submissions', icon: 'ri-file-list-3-line' },
    { id: 'history', label: 'Case History', icon: 'ri-history-line' },
  ];

  return (
    <EmployeeLayout title="Disciplinary">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2">
          <i className="ri-checkbox-circle-line"></i><span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="mb-5">
        <h2 className="text-lg font-bold text-gray-800">Disciplinary Module</h2>
        <p className="text-sm text-gray-500 mt-0.5">Report cases, view your submissions, and track case history</p>
      </div>

      <div className="flex gap-1 bg-white rounded-xl shadow-sm border border-gray-100 p-1 mb-5 w-fit">
        {TABS.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap transition-all ${activeTab === t.id ? 'text-white shadow-sm' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'}`}
            style={activeTab === t.id ? { background: '#b828a0' } : {}}>
            <div className="w-4 h-4 flex items-center justify-center"><i className={`${t.icon} text-xs`}></i></div>
            {t.label}
            {t.id === 'submissions' && mySubmissions.length > 0 && (
              <span className="ml-1 text-xs px-1.5 py-0.5 rounded-full font-bold" style={{ background: '#b828a0', color: 'white' }}>{mySubmissions.length}</span>
            )}
          </button>
        ))}
      </div>

      {activeTab === 'report' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 max-w-3xl">
          <div className="flex items-start gap-4 mb-6 p-4 bg-red-50 border border-red-200 rounded-xl">
            <i className="ri-shield-check-line text-red-600 text-2xl mt-0.5"></i>
            <div>
              <p className="font-semibold text-red-800">Report a Disciplinary Case</p>
              <p className="text-xs text-red-700 mt-1">All reports are handled confidentially by HR. Provide accurate and factual information. False reports may result in disciplinary action against the reporter.</p>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5">Employee Name *</label>
              <div className="relative">
                <select value={form.employeeName} onChange={e => {
                  const emp = employees.find(em => em.name === e.target.value);
                  setForm(f => ({ ...f, employeeName: e.target.value, department: emp?.dept || f.department }));
                }}
                  className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                  <option value="">Select employee...</option>
                  {employees.map(e => <option key={e.id} value={e.name}>{e.name} ({e.dept})</option>)}
                </select>
              </div>
              {errors.employeeName && <p className="text-xs text-red-500 mt-1">{errors.employeeName}</p>}
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5">Department *</label>
              <select value={form.department} onChange={e => setForm(f => ({ ...f, department: e.target.value }))}
                className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Select department...</option>
                {departments.map(d => <option key={d}>{d}</option>)}
              </select>
              {errors.department && <p className="text-xs text-red-500 mt-1">{errors.department}</p>}
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5">Complaint Type *</label>
              <select value={form.complaintType} onChange={e => setForm(f => ({ ...f, complaintType: e.target.value as ComplaintType }))}
                className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Select type...</option>
                {complaintTypes.map(t => <option key={t}>{t}</option>)}
              </select>
              {errors.complaintType && <p className="text-xs text-red-500 mt-1">{errors.complaintType}</p>}
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5">Severity Level</label>
              <div className="flex gap-2">
                {(['High', 'Medium', 'Low'] as const).map(s => (
                  <button key={s} onClick={() => setForm(f => ({ ...f, severity: s }))}
                    className="flex-1 py-2 rounded-lg text-xs font-semibold cursor-pointer whitespace-nowrap transition-all"
                    style={form.severity === s ? { background: SEVERITY_CONFIG[s].color, color: 'white' } : { background: SEVERITY_CONFIG[s].bg, color: SEVERITY_CONFIG[s].color }}>
                    {s}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5">Incident Date *</label>
              <input type="date" value={form.incidentDate} onChange={e => setForm(f => ({ ...f, incidentDate: e.target.value }))}
                max={new Date().toISOString().split('T')[0]}
                className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none" />
              {errors.incidentDate && <p className="text-xs text-red-500 mt-1">{errors.incidentDate}</p>}
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5">Witnesses (optional)</label>
              <input value={form.witnesses} onChange={e => setForm(f => ({ ...f, witnesses: e.target.value }))}
                placeholder="Names of witnesses, comma separated"
                className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none" />
            </div>

            <div className="md:col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1.5">Description of Incident * (min. 50 characters)</label>
              <textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} rows={5}
                maxLength={500} placeholder="Provide a detailed, factual description of the incident..."
                className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none" />
              <div className="flex justify-between mt-1">
                {errors.description && <p className="text-xs text-red-500">{errors.description}</p>}
                <p className="text-xs text-gray-400 ml-auto">{form.description.length}/500</p>
              </div>
            </div>

            <div className="md:col-span-2">
              <label className="flex items-center gap-3 cursor-pointer">
                <div className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${form.isConfidential ? 'border-pink-500 bg-pink-500' : 'border-gray-300'}`}
                  onClick={() => setForm(f => ({ ...f, isConfidential: !f.isConfidential }))}>
                  {form.isConfidential && <i className="ri-check-line text-white text-xs"></i>}
                </div>
                <div>
                  <p className="text-sm font-medium text-gray-700">Mark as Confidential</p>
                  <p className="text-xs text-gray-400">Only HR and senior management will have access to this report</p>
                </div>
              </label>
            </div>
          </div>

          <div className="flex gap-3 mt-6">
            <button onClick={() => setForm({ employeeName: '', employeeId: '', department: '', complaintType: '', severity: 'Medium', incidentDate: '', description: '', witnesses: '', isConfidential: false })}
              className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">
              Clear Form
            </button>
            <button onClick={handleSubmit}
              className="flex items-center gap-2 px-6 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
              style={{ background: '#b828a0' }}>
              <i className="ri-send-plane-line"></i> Submit Report
            </button>
          </div>
        </div>
      )}

      {activeTab === 'submissions' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100">
            <h3 className="font-semibold text-gray-700">My Submitted Cases</h3>
            <p className="text-xs text-gray-400 mt-0.5">{mySubmissions.length} case(s) submitted by you</p>
          </div>
          {mySubmissions.length === 0 ? (
            <div className="py-12 text-center text-gray-400">
              <i className="ri-file-list-3-line text-4xl block mb-2"></i>
              <p className="text-sm">No cases submitted yet</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Case No.</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Employee</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Complaint Type</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Severity</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Incident Date</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Submitted</th>
                    <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {mySubmissions.map(c => {
                    const sc = SEVERITY_CONFIG[c.severity];
                    return (
                      <tr key={c.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                        <td className="px-5 py-3 font-mono text-xs text-gray-500">{c.caseNumber}</td>
                        <td className="px-4 py-3">
                          <p className="font-medium text-gray-800">{c.employeeName}</p>
                          <p className="text-xs text-gray-400">{c.department}</p>
                        </td>
                        <td className="px-4 py-3 text-sm text-gray-600">{c.complaintType}</td>
                        <td className="px-4 py-3">
                          <span className="inline-flex px-2.5 py-1 rounded-full text-xs font-semibold whitespace-nowrap"
                            style={{ color: sc.color, background: sc.bg }}>{c.severity}</span>
                        </td>
                        <td className="px-4 py-3 text-xs text-gray-500">{c.incidentDate}</td>
                        <td className="px-4 py-3 text-xs text-gray-400">{c.createdAt.split('T')[0]}</td>
                        <td className="px-4 py-3 text-right">
                          <button onClick={() => setViewCase(c)}
                            className="text-xs font-medium cursor-pointer whitespace-nowrap" style={{ color: '#b828a0' }}>
                            View
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {activeTab === 'history' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100">
            <h3 className="font-semibold text-gray-700">Case History</h3>
            <p className="text-xs text-gray-400 mt-0.5">Cases involving you as subject or witness</p>
          </div>
          {caseHistory.length === 0 ? (
            <div className="py-12 text-center text-gray-400">
              <i className="ri-history-line text-4xl block mb-2"></i>
              <p className="text-sm">No case history found</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Case No.</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Complaint Type</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Severity</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Role</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Date</th>
                    <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {caseHistory.map(c => {
                    const sc = SEVERITY_CONFIG[c.severity];
                    const role = c.employeeName === user.name ? 'Subject' : 'Witness';
                    return (
                      <tr key={c.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                        <td className="px-5 py-3 font-mono text-xs text-gray-500">{c.caseNumber}</td>
                        <td className="px-4 py-3 text-sm text-gray-600">{c.complaintType}</td>
                        <td className="px-4 py-3">
                          <span className="inline-flex px-2.5 py-1 rounded-full text-xs font-semibold whitespace-nowrap"
                            style={{ color: sc.color, background: sc.bg }}>{c.severity}</span>
                        </td>
                        <td className="px-4 py-3">
                          <span className={`text-xs px-2 py-0.5 rounded-full font-semibold ${role === 'Subject' ? 'bg-red-100 text-red-700' : 'bg-blue-100 text-blue-700'}`}>
                            {role}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-xs text-gray-400">{c.incidentDate}</td>
                        <td className="px-4 py-3 text-right">
                          <button onClick={() => setViewCase(c)}
                            className="text-xs font-medium cursor-pointer whitespace-nowrap" style={{ color: '#b828a0' }}>
                            View
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {viewCase && (
        <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-2xl max-h-[90vh] overflow-y-auto">
            <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b828a0' }}>
              <div>
                <h3 className="font-bold text-white">{viewCase.caseNumber}</h3>
                <p className="text-pink-200 text-xs">{viewCase.complaintType}</p>
              </div>
              <button onClick={() => setViewCase(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="grid grid-cols-2 gap-4">
                <div><p className="text-xs text-gray-400">Employee</p><p className="font-semibold text-gray-800">{viewCase.employeeName}</p></div>
                <div><p className="text-xs text-gray-400">Department</p><p className="font-semibold text-gray-800">{viewCase.department}</p></div>
                <div><p className="text-xs text-gray-400">Severity</p>
                  <span className="inline-flex px-2.5 py-1 rounded-full text-xs font-semibold"
                    style={{ color: SEVERITY_CONFIG[viewCase.severity].color, background: SEVERITY_CONFIG[viewCase.severity].bg }}>
                    {viewCase.severity}
                  </span>
                </div>
                <div><p className="text-xs text-gray-400">Incident Date</p><p className="font-semibold text-gray-800">{viewCase.incidentDate}</p></div>
                <div><p className="text-xs text-gray-400">Reported By</p><p className="font-semibold text-gray-800">{viewCase.createdBy}</p></div>
                <div><p className="text-xs text-gray-400">Confidential</p><p className="font-semibold text-gray-800">{viewCase.isConfidential ? 'Yes' : 'No'}</p></div>
              </div>
              <div>
                <p className="text-xs text-gray-400 mb-1">Description</p>
                <p className="text-sm text-gray-700 bg-gray-50 rounded-xl p-3">{viewCase.description}</p>
              </div>
              {viewCase.witnesses && (
                <div>
                  <p className="text-xs text-gray-400 mb-1">Witnesses</p>
                  <p className="text-sm text-gray-700">{viewCase.witnesses}</p>
                </div>
              )}
            </div>
            <div className="px-6 pb-6">
              <button onClick={() => setViewCase(null)} className="w-full py-3 rounded-xl border border-gray-200 text-sm font-medium text-gray-600 cursor-pointer whitespace-nowrap">Close</button>
            </div>
          </div>
        </div>
      )}
    </EmployeeLayout>
  );
}
