'use client';
import { useState } from 'react';
import { DisciplinaryCase, SeverityLevel, ComplaintType, complaintTypes } from './disciplinaryData';

const PRIMARY = '#B22698';
const PRIMARY_LIGHT = '#F9E6F5';

interface Props {
  cases: DisciplinaryCase[];
  onView: (c: DisciplinaryCase) => void;
  onNew: () => void;
  severityFilter: string;
  onSeverityFilter: (s: string) => void;
  canSeeConfidential: boolean;
  currentUserId: string;
}

const severityConfig = {
  High: { dot: '🔴', color: '#C62828', light: '#FFEBEE' },
  Medium: { dot: '🟠', color: '#E65100', light: '#FFF3E0' },
  Low: { dot: '🟢', color: '#2E7D32', light: '#E8F5E9' },
};

const PAGE_SIZES = [10, 25, 50, 100];

export default function CaseRegisterTab({ cases, onView, onNew, severityFilter, onSeverityFilter, canSeeConfidential, currentUserId }: Props) {
  const [search, setSearch] = useState('');
  const [filterType, setFilterType] = useState<ComplaintType | 'All'>('All');
  const [pageSize, setPageSize] = useState(10);
  const [page, setPage] = useState(1);

  const visibleCases = cases.filter(c => {
    if (c.isConfidential && !canSeeConfidential && c.createdBy !== currentUserId) return false;
    return true;
  });

  const filtered = visibleCases.filter(c => {
    const matchSearch = c.caseNumber.toLowerCase().includes(search.toLowerCase()) ||
      c.employeeName.toLowerCase().includes(search.toLowerCase()) ||
      c.complaintType.toLowerCase().includes(search.toLowerCase());
    const matchSev = severityFilter === 'All' || c.severity === severityFilter;
    const matchType = filterType === 'All' || c.complaintType === filterType;
    return matchSearch && matchSev && matchType;
  });

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const paginated = filtered.slice((page - 1) * pageSize, page * pageSize);

  const exportCSV = () => {
    const headers = ['Case #', 'Employee Name', 'Employee ID', 'Department', 'Complaint Type', 'Severity', 'Incident Date', 'Confidential', 'Created By', 'Created At'];
    const rows = filtered.map(c => [
      c.caseNumber, c.employeeName, c.employeeId, c.department,
      c.complaintType, c.severity, c.incidentDate,
      c.isConfidential ? 'Yes' : 'No', c.createdBy, c.createdAt,
    ]);
    const csv = [headers, ...rows].map(r => r.map(v => `"${v}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'disciplinary_cases.csv'; a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div>
      <div className="flex flex-wrap gap-3 mb-5 items-center justify-between">
        <div className="flex flex-wrap gap-2 items-center">
          <div className="relative">
            <input value={search} onChange={e => { setSearch(e.target.value); setPage(1); }}
              placeholder="Search case #, employee, type..."
              className="border rounded-xl pl-9 pr-3 py-2 text-sm outline-none w-60"
              style={{ borderColor: search ? PRIMARY : '#e5e7eb' }} />
            <div className="w-4 h-4 flex items-center justify-center absolute left-3 top-1/2 -translate-y-1/2">
              <i className="ri-search-line text-gray-400 text-sm"></i>
            </div>
          </div>
          <div className="relative">
            <select value={severityFilter} onChange={e => { onSeverityFilter(e.target.value); setPage(1); }}
              className="border rounded-xl px-3 py-2 text-sm outline-none cursor-pointer pr-8 appearance-none"
              style={{ borderColor: severityFilter !== 'All' ? PRIMARY : '#e5e7eb' }}>
              <option value="All">All Severities</option>
              <option value="High">🔴 High</option>
              <option value="Medium">🟠 Medium</option>
              <option value="Low">🟢 Low</option>
            </select>
            <div className="w-4 h-4 flex items-center justify-center absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none">
              <i className="ri-arrow-down-s-line text-gray-400 text-sm"></i>
            </div>
          </div>
          <div className="relative">
            <select value={filterType} onChange={e => { setFilterType(e.target.value as any); setPage(1); }}
              className="border rounded-xl px-3 py-2 text-sm outline-none cursor-pointer pr-8 appearance-none"
              style={{ borderColor: filterType !== 'All' ? PRIMARY : '#e5e7eb' }}>
              <option value="All">All Types</option>
              {complaintTypes.map(ct => <option key={ct} value={ct}>{ct}</option>)}
            </select>
            <div className="w-4 h-4 flex items-center justify-center absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none">
              <i className="ri-arrow-down-s-line text-gray-400 text-sm"></i>
            </div>
          </div>
        </div>
        <div className="flex gap-2">
          <button onClick={exportCSV}
            className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-sm font-semibold border-2 cursor-pointer whitespace-nowrap hover:bg-purple-50 transition-colors"
            style={{ borderColor: PRIMARY, color: PRIMARY }}>
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-download-line text-base"></i></div>
            Export CSV
          </button>
          <button onClick={onNew}
            className="flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-semibold text-white cursor-pointer whitespace-nowrap shadow-sm hover:opacity-90 transition-opacity"
            style={{ background: PRIMARY }}>
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-add-line text-base"></i></div>
            New Case
          </button>
        </div>
      </div>

      <div className="rounded-2xl border overflow-hidden" style={{ borderColor: '#E9D5F5' }}>
        <table className="w-full text-sm">
          <thead>
            <tr style={{ background: PRIMARY_LIGHT }}>
              <th className="text-left px-4 py-3 text-xs font-bold uppercase tracking-wide" style={{ color: PRIMARY }}>Case #</th>
              <th className="text-left px-4 py-3 text-xs font-bold uppercase tracking-wide" style={{ color: PRIMARY }}>Employee Name</th>
              <th className="text-left px-4 py-3 text-xs font-bold uppercase tracking-wide" style={{ color: PRIMARY }}>Complaint Type</th>
              <th className="text-left px-4 py-3 text-xs font-bold uppercase tracking-wide" style={{ color: PRIMARY }}>Severity</th>
              <th className="text-left px-4 py-3 text-xs font-bold uppercase tracking-wide" style={{ color: PRIMARY }}>Incident Date</th>
              <th className="px-4 py-3 text-xs font-bold uppercase tracking-wide text-center" style={{ color: PRIMARY }}>Action</th>
            </tr>
          </thead>
          <tbody>
            {paginated.length === 0 && (
              <tr>
                <td colSpan={6} className="text-center py-16 text-gray-400">
                  <div className="w-12 h-12 flex items-center justify-center mx-auto mb-3">
                    <i className="ri-file-list-3-line text-4xl text-gray-200"></i>
                  </div>
                  <p className="text-sm">No cases found</p>
                </td>
              </tr>
            )}
            {paginated.map((c) => {
              const sv = severityConfig[c.severity];
              return (
                <tr key={c.id}
                  className="border-t transition-colors hover:bg-purple-50/30 cursor-pointer"
                  style={{ borderColor: '#F3E8FB' }}
                  onClick={() => onView(c)}>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <span className="font-mono font-bold text-gray-800">{c.caseNumber}</span>
                      {c.isConfidential && (
                        <span className="w-4 h-4 flex items-center justify-center" title="Confidential">
                          <i className="ri-lock-fill text-xs text-gray-400"></i>
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <p className="font-semibold text-gray-800">{c.employeeName}</p>
                    <p className="text-xs text-gray-400 font-mono">{c.employeeId}</p>
                  </td>
                  <td className="px-4 py-3 text-gray-600">{c.complaintType}</td>
                  <td className="px-4 py-3">
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold"
                      style={{ background: sv.light, color: sv.color }}>
                      {sv.dot} {c.severity}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-gray-600">{c.incidentDate}</td>
                  <td className="px-4 py-3 text-center" onClick={e => e.stopPropagation()}>
                    <button onClick={() => onView(c)}
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold cursor-pointer whitespace-nowrap transition-colors hover:opacity-80"
                      style={{ background: PRIMARY_LIGHT, color: PRIMARY }}>
                      <div className="w-3 h-3 flex items-center justify-center"><i className="ri-eye-line text-xs"></i></div>
                      View
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="flex items-center justify-between mt-4">
        <div className="flex items-center gap-2 text-sm text-gray-500">
          <span>Rows per page:</span>
          <div className="relative">
            <select value={pageSize} onChange={e => { setPageSize(Number(e.target.value)); setPage(1); }}
              className="border border-gray-200 rounded-lg px-2 py-1 text-sm outline-none cursor-pointer pr-6 appearance-none">
              {PAGE_SIZES.map(s => <option key={s} value={s}>{s}</option>)}
            </select>
            <div className="w-4 h-4 flex items-center justify-center absolute right-1 top-1/2 -translate-y-1/2 pointer-events-none">
              <i className="ri-arrow-down-s-line text-gray-400 text-xs"></i>
            </div>
          </div>
          <span>Showing {Math.min((page - 1) * pageSize + 1, filtered.length)}–{Math.min(page * pageSize, filtered.length)} of {filtered.length}</span>
        </div>
        <div className="flex items-center gap-1">
          <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}
            className="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-200 cursor-pointer disabled:opacity-40 hover:bg-gray-50 transition-colors">
            <i className="ri-arrow-left-s-line text-gray-600 text-base"></i>
          </button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            const p = Math.max(1, Math.min(page - 2, totalPages - 4)) + i;
            return (
              <button key={p} onClick={() => setPage(p)}
                className="w-8 h-8 flex items-center justify-center rounded-lg text-sm font-medium cursor-pointer transition-colors"
                style={page === p ? { background: PRIMARY, color: '#fff' } : { color: '#555' }}>
                {p}
              </button>
            );
          })}
          <button onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={page === totalPages}
            className="w-8 h-8 flex items-center justify-center rounded-lg border border-gray-200 cursor-pointer disabled:opacity-40 hover:bg-gray-50 transition-colors">
            <i className="ri-arrow-right-s-line text-gray-600 text-base"></i>
          </button>
        </div>
      </div>
    </div>
  );
}
