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

const PRIMARY = '#B22698';
const PRIMARY_LIGHT = '#F9E6F5';
const YELLOW = '#FFC107';
const DARK = '#212121';

interface Props {
  onClose: () => void;
  onSave: (c: DisciplinaryCase) => void;
  isPrivilegedUser: boolean;
  currentUser: string;
  currentUserRole: string;
}

export default function NewCaseModal({ onClose, onSave, isPrivilegedUser, currentUser, currentUserRole }: Props) {
  const [employeeSearch, setEmployeeSearch] = useState('');
  const [showDropdown, setShowDropdown] = useState(false);
  const [selectedEmployee, setSelectedEmployee] = useState<{ name: string; id: string; dept: string } | null>(null);
  const [form, setForm] = useState({
    complaintType: '' as any,
    severity: 'Medium' as 'High' | 'Medium' | 'Low',
    incidentDate: '',
    description: '',
    witnesses: '',
    isConfidential: false,
  });
  const [evidenceFiles, setEvidenceFiles] = useState<File[]>([]);
  const [fileError, setFileError] = useState('');

  const filteredEmployees = employees.filter(e =>
    e.name.toLowerCase().includes(employeeSearch.toLowerCase()) ||
    e.id.toLowerCase().includes(employeeSearch.toLowerCase())
  );

  const year = new Date().getFullYear();
  const seq = String(Math.floor(Math.random() * 900) + 100).padStart(3, '0');
  const caseNumber = `DC-${year}-${seq}`;

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    setFileError('');
    const valid = files.filter(f => {
      const ext = f.name.split('.').pop()?.toLowerCase();
      const allowed = ['pdf', 'doc', 'docx', 'jpg', 'png'];
      if (!allowed.includes(ext || '')) { setFileError('Only PDF, DOC, DOCX, JPG, PNG allowed.'); return false; }
      if (f.size > 10 * 1024 * 1024) { setFileError('Max file size is 10MB.'); return false; }
      return true;
    });
    setEvidenceFiles(prev => [...prev, ...valid]);
  };

  const removeFile = (i: number) => setEvidenceFiles(prev => prev.filter((_, idx) => idx !== i));

  const canSubmit = selectedEmployee && form.complaintType && form.incidentDate && form.description.trim().length > 0;

  const handleSave = () => {
    if (!canSubmit) return;
    const newCase: DisciplinaryCase = {
      id: Date.now().toString(),
      caseNumber,
      employeeName: selectedEmployee!.name,
      employeeId: selectedEmployee!.id,
      department: selectedEmployee!.dept,
      complaintType: form.complaintType,
      severity: form.severity,
      incidentDate: form.incidentDate,
      description: form.description,
      witnesses: form.witnesses || undefined,
      evidenceFiles: evidenceFiles.map(f => ({
        name: f.name,
        size: f.size > 1024 * 1024 ? `${(f.size / 1024 / 1024).toFixed(1)} MB` : `${Math.round(f.size / 1024)} KB`,
        type: f.name.split('.').pop()?.toLowerCase() || 'file',
      })),
      isConfidential: isPrivilegedUser ? false : form.isConfidential,
      createdBy: currentUser,
      createdByRole: currentUserRole,
      createdAt: new Date().toISOString(),
    };
    onSave(newCase);
  };

  const f = (field: string, val: any) => setForm(p => ({ ...p, [field]: val }));

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[92vh] overflow-y-auto">
        <div className="flex items-center justify-between p-5 border-b sticky top-0 bg-white z-10 rounded-t-2xl"
          style={{ borderColor: '#E9D5F5' }}>
          <div>
            <h2 className="text-lg font-bold" style={{ color: DARK }}>New Disciplinary Case</h2>
            <p className="text-xs text-gray-500 mt-0.5">
              Case No: <span className="font-mono font-bold" style={{ color: PRIMARY }}>{caseNumber}</span>
            </p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 cursor-pointer">
            <i className="ri-close-line text-gray-500 text-lg"></i>
          </button>
        </div>

        <div className="p-5 space-y-5">
          {!isPrivilegedUser && (
            <div className="p-3 rounded-xl text-sm flex items-start gap-2" style={{ background: PRIMARY_LIGHT, color: PRIMARY }}>
              <div className="w-4 h-4 flex items-center justify-center mt-0.5 flex-shrink-0">
                <i className="ri-information-line text-base"></i>
              </div>
              <span>This case will be visible to HR, Admin, Finance Officers, HODs, and you.</span>
            </div>
          )}
          {isPrivilegedUser && (
            <div className="p-3 rounded-xl text-sm flex items-start gap-2" style={{ background: PRIMARY_LIGHT, color: PRIMARY }}>
              <div className="w-4 h-4 flex items-center justify-center mt-0.5 flex-shrink-0">
                <i className="ri-information-line text-base"></i>
              </div>
              <span>This case will be visible to HR, Admin, Finance Officers, HODs, and the reporter.</span>
            </div>
          )}

          <div>
            <label className="text-xs font-semibold text-gray-600 mb-1.5 block">Employee Involved *</label>
            <div className="relative">
              <input
                value={selectedEmployee ? `${selectedEmployee.name} (${selectedEmployee.id})` : employeeSearch}
                onChange={e => { setEmployeeSearch(e.target.value); setSelectedEmployee(null); setShowDropdown(true); }}
                onFocus={() => setShowDropdown(true)}
                placeholder="Search by name or employee ID..."
                className="w-full border rounded-xl px-4 py-2.5 text-sm outline-none pr-10"
                style={{ borderColor: selectedEmployee ? PRIMARY : '#e5e7eb' }}
              />
              <div className="w-5 h-5 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2">
                {selectedEmployee
                  ? <i className="ri-check-line text-base" style={{ color: PRIMARY }}></i>
                  : <i className="ri-search-line text-gray-400 text-base"></i>
                }
              </div>
              {showDropdown && !selectedEmployee && filteredEmployees.length > 0 && (
                <div className="absolute top-full left-0 right-0 bg-white border border-gray-200 rounded-xl shadow-lg z-20 max-h-48 overflow-y-auto mt-1">
                  {filteredEmployees.map(emp => (
                    <button key={emp.id} onClick={() => { setSelectedEmployee(emp); setEmployeeSearch(''); setShowDropdown(false); }}
                      className="w-full text-left px-4 py-2.5 hover:bg-gray-50 cursor-pointer flex items-center justify-between">
                      <span className="text-sm font-medium text-gray-800">{emp.name}</span>
                      <span className="text-xs text-gray-400">{emp.id} • {emp.dept}</span>
                    </button>
                  ))}
                </div>
              )}
            </div>
            {selectedEmployee && (
              <div className="mt-2 flex items-center gap-2 text-xs text-gray-500">
                <i className="ri-building-line"></i>
                <span>{selectedEmployee.dept}</span>
                <span className="text-gray-300">|</span>
                <span className="font-mono">{selectedEmployee.id}</span>
                <button onClick={() => setSelectedEmployee(null)} className="ml-auto text-red-400 hover:text-red-600 cursor-pointer">
                  <i className="ri-close-circle-line"></i> Clear
                </button>
              </div>
            )}
          </div>

          <div>
            <label className="text-xs font-semibold text-gray-600 mb-1.5 block">Complaint Type *</label>
            <div className="relative">
              <select value={form.complaintType} onChange={e => f('complaintType', e.target.value)}
                className="w-full border rounded-xl px-4 py-2.5 text-sm outline-none appearance-none cursor-pointer pr-10"
                style={{ borderColor: form.complaintType ? PRIMARY : '#e5e7eb' }}>
                <option value="">Select complaint type</option>
                {complaintTypes.map(ct => <option key={ct} value={ct}>{ct}</option>)}
              </select>
              <div className="w-5 h-5 flex items-center justify-center absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
                <i className="ri-arrow-down-s-line text-gray-400 text-base"></i>
              </div>
            </div>
          </div>

          <div>
            <label className="text-xs font-semibold text-gray-600 mb-2 block">Severity *</label>
            <div className="flex gap-3">
              {([
                { val: 'High', icon: 'ri-error-warning-fill', color: '#C62828', light: '#FFEBEE' },
                { val: 'Medium', icon: 'ri-alert-fill', color: '#E65100', light: '#FFF3E0' },
                { val: 'Low', icon: 'ri-information-fill', color: '#2E7D32', light: '#E8F5E9' },
              ] as const).map(s => (
                <button key={s.val} onClick={() => f('severity', s.val)}
                  className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-semibold border-2 cursor-pointer transition-all whitespace-nowrap"
                  style={{
                    background: form.severity === s.val ? s.color : s.light,
                    borderColor: form.severity === s.val ? s.color : 'transparent',
                    color: form.severity === s.val ? '#fff' : s.color,
                  }}>
                  <div className="w-4 h-4 flex items-center justify-center">
                    <i className={`${s.icon} text-base`}></i>
                  </div>
                  {s.val}
                </button>
              ))}
            </div>
          </div>

          <div>
            <label className="text-xs font-semibold text-gray-600 mb-1.5 block">Date of Incident *</label>
            <input type="date" value={form.incidentDate} onChange={e => f('incidentDate', e.target.value)}
              max={new Date().toISOString().split('T')[0]}
              className="w-full border rounded-xl px-4 py-2.5 text-sm outline-none"
              style={{ borderColor: form.incidentDate ? PRIMARY : '#e5e7eb' }} />
          </div>

          <div>
            <label className="text-xs font-semibold text-gray-600 mb-1.5 block">Description *</label>
            <textarea value={form.description} onChange={e => f('description', e.target.value)}
              rows={4} placeholder="Describe the incident in detail..."
              maxLength={500}
              className="w-full border rounded-xl px-4 py-2.5 text-sm outline-none resize-none"
              style={{ borderColor: form.description ? PRIMARY : '#e5e7eb' }} />
            <p className="text-xs text-gray-400 text-right mt-1">{form.description.length}/500</p>
          </div>

          <div>
            <label className="text-xs font-semibold text-gray-600 mb-1.5 block">Witnesses <span className="font-normal text-gray-400">(optional)</span></label>
            <input value={form.witnesses} onChange={e => f('witnesses', e.target.value)}
              placeholder="e.g. John Doe, Jane Smith"
              className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none" />
          </div>

          <div>
            <label className="text-xs font-semibold text-gray-600 mb-1.5 block">
              Attach Evidence <span className="font-normal text-gray-400">(optional — PDF, DOC, DOCX, JPG, PNG, max 10MB)</span>
            </label>
            <label className="flex items-center gap-3 border-2 border-dashed rounded-xl px-4 py-3 cursor-pointer hover:bg-gray-50 transition-colors"
              style={{ borderColor: '#d1d5db' }}>
              <div className="w-8 h-8 flex items-center justify-center rounded-lg" style={{ background: PRIMARY_LIGHT }}>
                <i className="ri-upload-cloud-line text-lg" style={{ color: PRIMARY }}></i>
              </div>
              <div>
                <p className="text-sm font-medium text-gray-700">Click to upload files</p>
                <p className="text-xs text-gray-400">PDF, DOC, DOCX, JPG, PNG up to 10MB each</p>
              </div>
              <input type="file" multiple accept=".pdf,.doc,.docx,.jpg,.png" onChange={handleFileChange} className="hidden" />
            </label>
            {fileError && <p className="text-xs text-red-500 mt-1">{fileError}</p>}
            {evidenceFiles.length > 0 && (
              <div className="mt-2 space-y-1.5">
                {evidenceFiles.map((file, i) => (
                  <div key={i} className="flex items-center gap-2 px-3 py-2 rounded-lg" style={{ background: PRIMARY_LIGHT }}>
                    <div className="w-4 h-4 flex items-center justify-center">
                      <i className="ri-file-line text-sm" style={{ color: PRIMARY }}></i>
                    </div>
                    <span className="text-xs text-gray-700 flex-1 truncate">{file.name}</span>
                    <span className="text-xs text-gray-400">{file.size > 1024 * 1024 ? `${(file.size / 1024 / 1024).toFixed(1)} MB` : `${Math.round(file.size / 1024)} KB`}</span>
                    <button onClick={() => removeFile(i)} className="w-4 h-4 flex items-center justify-center cursor-pointer text-red-400 hover:text-red-600">
                      <i className="ri-close-line text-sm"></i>
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {!isPrivilegedUser && (
            <div className="p-4 rounded-xl border-2" style={{ borderColor: YELLOW, background: '#FFFDE7' }}>
              <label className="flex items-start gap-3 cursor-pointer">
                <input type="checkbox" checked={form.isConfidential} onChange={e => f('isConfidential', e.target.checked)}
                  className="w-4 h-4 mt-0.5 cursor-pointer flex-shrink-0" />
                <div>
                  <p className="text-sm font-semibold" style={{ color: DARK }}>Mark this case as CONFIDENTIAL</p>
                  <p className="text-xs text-gray-500 mt-0.5">If checked, this case will only be visible to HR, Admin, Finance Officers, HODs, and you.</p>
                </div>
              </label>
            </div>
          )}
        </div>

        <div className="flex gap-3 p-5 border-t" style={{ borderColor: '#E9D5F5' }}>
          <button onClick={onClose}
            className="flex-1 py-2.5 rounded-xl border-2 text-sm font-semibold cursor-pointer whitespace-nowrap hover:bg-gray-50 transition-colors"
            style={{ borderColor: '#e5e7eb', color: '#555' }}>
            Cancel
          </button>
          <button onClick={handleSave} disabled={!canSubmit}
            className="flex-1 py-2.5 rounded-xl text-sm font-semibold text-white cursor-pointer whitespace-nowrap transition-all disabled:opacity-40 disabled:cursor-not-allowed"
            style={{ background: PRIMARY }}>
            Create Case
          </button>
        </div>
      </div>
    </div>
  );
}
