import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  FaArrowLeft, FaSave, FaEdit, FaTimes,
  FaCheckCircle, FaTimesCircle, FaSpinner, FaUserTie,
  FaChevronDown, FaChevronRight,
} from 'react-icons/fa';
import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import masterService, { Employee } from '../services/masterService';
import LinkField from '../components/LinkField';
import ActivityLog from '../components/ActivityLog';

// ─── Helpers ─────────────────────────────────────────────────────────────────
const FL: React.FC<{ children: React.ReactNode; required?: boolean }> = ({ children, required }) => (
  <label className="block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">
    {children}{required && <span className="text-red-500 ml-0.5">*</span>}
  </label>
);
const RV: React.FC<{ children?: React.ReactNode }> = ({ children }) => (
  <div className="px-3 py-2 text-sm text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-800/60 rounded-lg min-h-[38px] flex items-center">
    {children || <span className="text-gray-400">-</span>}
  </div>
);
const inputCls = 'w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-teal-400';

const CollapsibleSection: React.FC<{ title: string; children: React.ReactNode; defaultOpen?: boolean }> = ({ title, children, defaultOpen = true }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="border-t border-gray-100 dark:border-gray-700">
      <button type="button" onClick={() => setOpen(o => !o)}
        className="w-full flex items-center justify-between px-6 py-3 hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors">
        <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">{title}</span>
        {open ? <FaChevronDown className="text-gray-400 text-xs" /> : <FaChevronRight className="text-gray-400 text-xs" />}
      </button>
      {open && <div className="px-6 pb-5">{children}</div>}
    </div>
  );
};

const statusBadge = (s?: string) => {
  switch (s) {
    case 'Active':   return 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300';
    case 'Inactive': return 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400';
    case 'Left':     return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300';
    case 'On Leave': return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300';
    default:         return 'bg-gray-100 text-gray-600';
  }
};

// ─── Component ────────────────────────────────────────────────────────────────
const EmployeeDetail: React.FC = () => {
  const { employeeName } = useParams<{ employeeName: string }>();
  const navigate = useNavigate();
  const isNew = employeeName === 'new';

  const [employee, setEmployee] = useState<Employee | null>(null);
  const [loading, setLoading]   = useState(!isNew);
  const [saving, setSaving]     = useState(false);
  const [isEditing, setIsEditing] = useState(isNew);
  const [error, setError]       = useState('');

  const emptyForm: Partial<Employee> = {
    first_name: '', middle_name: '', last_name: '', salutation: '',
    gender: '', date_of_birth: '', date_of_joining: '', status: 'Active',
    company: '', designation: '', branch: '', department: '', reports_to: '', employee_number: '',
  };
  const [form, setForm] = useState<Partial<Employee>>(emptyForm);

  const syncForm = useCallback((e: Employee) => {
    setForm({
      first_name:      e.first_name      || '',
      middle_name:     e.middle_name     || '',
      last_name:       e.last_name       || '',
      salutation:      e.salutation      || '',
      gender:          e.gender          || '',
      date_of_birth:   e.date_of_birth   || '',
      date_of_joining: e.date_of_joining || '',
      status:          e.status          || 'Active',
      company:         e.company         || '',
      designation:     e.designation     || '',
      branch:          e.branch          || '',
      department:      e.department      || '',
      reports_to:      e.reports_to      || '',
      employee_number: e.employee_number || '',
    });
  }, []);

  useEffect(() => {
    if (!isNew && employeeName) {
      setLoading(true);
      masterService.getEmployee(employeeName)
        .then(e => { setEmployee(e); syncForm(e); })
        .catch(e => setError(e.message))
        .finally(() => setLoading(false));
    }
  }, [employeeName, isNew, syncForm]);

  const set = (k: keyof Employee, v: any) => setForm(f => ({ ...f, [k]: v }));

  const handleSave = async () => {
    if (!form.first_name?.trim()) { toast.error('First Name is required'); return; }
    if (!form.gender)             { toast.error('Gender is required'); return; }
    if (!form.date_of_birth)      { toast.error('Date of Birth is required'); return; }
    if (!form.date_of_joining)    { toast.error('Date of Joining is required'); return; }

    setSaving(true);
    try {
      if (isNew) {
        const created = await masterService.createEmployee(form);
        toast.success('Employee created', { icon: <FaCheckCircle /> });
        navigate(`/employees/${encodeURIComponent(created.name)}`);
      } else {
        const updated = await masterService.updateEmployee(employeeName!, form);
        toast.success('Employee updated', { icon: <FaCheckCircle /> });
        setEmployee(updated); syncForm(updated); setIsEditing(false);
      }
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Save failed', { icon: <FaTimesCircle /> });
    } finally {
      setSaving(false);
    }
  };

  const handleCancel = () => { if (employee) syncForm(employee); setIsEditing(false); };
  const editable = isNew || isEditing;

  const displayName = employee?.employee_name
    || [employee?.first_name, employee?.last_name].filter(Boolean).join(' ')
    || employeeName;

  if (loading) return <div className="flex justify-center items-center min-h-[400px]"><FaSpinner className="animate-spin text-teal-500 text-3xl" /></div>;

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 px-6 py-6">
      <ToastContainer position="top-right" autoClose={3500} />

      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm mb-6 text-gray-500 dark:text-gray-400">
        <button onClick={() => navigate('/projects')} className="hover:text-teal-600">Project Management</button>
        <span>/</span>
        <button onClick={() => navigate('/employees')} className="hover:text-teal-600">Employees</button>
        <span>/</span>
        <span className="text-gray-700 dark:text-gray-300">{isNew ? 'New Employee' : displayName}</span>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden">

        {/* Header */}
        <div className="px-6 py-4 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between gap-4 flex-wrap">
          <div className="flex items-center gap-3">
            <button onClick={() => navigate('/employees')} className="text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"><FaArrowLeft /></button>
            <div className="w-10 h-10 rounded-xl bg-teal-600 flex items-center justify-center flex-shrink-0">
              <FaUserTie className="text-white" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-gray-900 dark:text-white">
                {isNew ? 'New Employee' : displayName}
              </h1>
              {!isNew && employee && (
                <span className={`text-xs px-2 py-0.5 rounded font-medium ${statusBadge(employee.status)}`}>
                  {employee.status || 'Active'}
                </span>
              )}
            </div>
          </div>
          <div className="flex gap-2">
            {!isNew && !isEditing && (
              <button onClick={() => setIsEditing(true)} className="flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 text-sm">
                <FaEdit /> Edit
              </button>
            )}
            {editable && (
              <>
                <button onClick={handleSave} disabled={saving} className="flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50 text-sm font-medium">
                  {saving ? <FaSpinner className="animate-spin" /> : <FaSave />}
                  {saving ? 'Saving…' : 'Save'}
                </button>
                {!isNew && <button onClick={handleCancel} className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 text-sm"><FaTimes /></button>}
              </>
            )}
          </div>
        </div>

        {error && <div className="mx-6 mt-4 p-3 bg-red-50 dark:bg-red-900/20 rounded text-red-700 dark:text-red-300 text-sm">{error}</div>}

        {/* ── Overview ── */}
        <div className="p-6 grid grid-cols-1 sm:grid-cols-3 gap-x-6 gap-y-4 border-b border-gray-100 dark:border-gray-700">

          {/* Series (read-only) */}
          <div>
            <FL>Series</FL>
            <RV>HR-EMP-</RV>
          </div>

          {/* Gender */}
          <div>
            <FL required>Gender</FL>
            {editable
              ? <select value={form.gender || ''} onChange={e => set('gender', e.target.value)} className={inputCls}>
                  <option value="">Select gender</option>
                  <option>Male</option><option>Female</option><option>Other</option><option>Prefer not to say</option>
                </select>
              : <RV>{form.gender}</RV>}
          </div>

          {/* Date of Joining */}
          <div>
            <FL required>Date of Joining</FL>
            {editable
              ? <input type="date" value={form.date_of_joining || ''} onChange={e => set('date_of_joining', e.target.value)} className={inputCls} />
              : <RV>{form.date_of_joining}</RV>}
          </div>

          {/* First Name */}
          <div>
            <FL required>First Name</FL>
            {editable
              ? <input value={form.first_name || ''} onChange={e => set('first_name', e.target.value)} className={inputCls} placeholder="First name" />
              : <RV>{form.first_name}</RV>}
          </div>

          {/* Date of Birth */}
          <div>
            <FL required>Date of Birth</FL>
            {editable
              ? <input type="date" value={form.date_of_birth || ''} onChange={e => set('date_of_birth', e.target.value)} className={inputCls} />
              : <RV>{form.date_of_birth}</RV>}
          </div>

          {/* Status */}
          <div>
            <FL>Status</FL>
            {editable
              ? <select value={form.status || 'Active'} onChange={e => set('status', e.target.value)} className={inputCls}>
                  <option>Active</option><option>Inactive</option><option>Left</option><option>On Leave</option>
                </select>
              : <RV>
                  <span className={`px-2 py-0.5 rounded text-xs font-medium ${statusBadge(form.status)}`}>{form.status || 'Active'}</span>
                </RV>}
          </div>

          {/* Middle Name */}
          <div>
            <FL>Middle Name</FL>
            {editable
              ? <input value={form.middle_name || ''} onChange={e => set('middle_name', e.target.value)} className={inputCls} placeholder="Middle name" />
              : <RV>{form.middle_name}</RV>}
          </div>

          {/* Salutation */}
          <div>
            <FL>Salutation</FL>
            {editable
              ? <select value={form.salutation || ''} onChange={e => set('salutation', e.target.value)} className={inputCls}>
                  <option value="">Select</option>
                  <option>Mr.</option><option>Ms.</option><option>Mrs.</option><option>Dr.</option><option>Prof.</option>
                </select>
              : <RV>{form.salutation}</RV>}
          </div>

          {/* Last Name */}
          <div>
            <FL>Last Name</FL>
            {editable
              ? <input value={form.last_name || ''} onChange={e => set('last_name', e.target.value)} className={inputCls} placeholder="Last name" />
              : <RV>{form.last_name}</RV>}
          </div>
        </div>

        {/* ── Company Details ── */}
        <CollapsibleSection title="Company Details">
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-x-6 gap-y-4">

            {/* Hospital (= company field) */}
            <div>
              <FL required>Hospital</FL>
              {editable
                ? <LinkField label="Hospital" hideLabel doctype="Company" value={form.company || ''} onChange={v => set('company', v)} placeholder="Select hospital…" />
                : <RV>{form.company}</RV>}
            </div>

            {/* Designation */}
            <div>
              <FL>Designation</FL>
              {editable
                ? <LinkField label="Designation" hideLabel doctype="Designation" value={form.designation || ''} onChange={v => set('designation', v)} placeholder="Select designation…" />
                : <RV>{form.designation}</RV>}
            </div>

            {/* Department */}
            <div>
              <FL>Department</FL>
              {editable
                ? <LinkField label="Department" hideLabel doctype="Department" value={form.department || ''} onChange={v => set('department', v)} placeholder="Select department…" />
                : <RV>{form.department}</RV>}
            </div>

            {/* Employee Number */}
            <div>
              <FL>Employee Number</FL>
              {editable
                ? <input value={form.employee_number || ''} onChange={e => set('employee_number', e.target.value)} className={inputCls} placeholder="e.g. EMP-001" />
                : <RV>{form.employee_number}</RV>}
            </div>
          </div>
        </CollapsibleSection>

        {/* ── Meta ── */}
        {!isNew && employee && (
          <div className="px-6 py-4 border-t border-gray-100 dark:border-gray-700 grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs text-gray-400 dark:text-gray-500">
            <div><span className="font-medium block text-gray-500 dark:text-gray-400">Created By</span>{employee.owner}</div>
            <div><span className="font-medium block text-gray-500 dark:text-gray-400">Created</span>{employee.creation ? new Date(employee.creation).toLocaleString() : '-'}</div>
            <div><span className="font-medium block text-gray-500 dark:text-gray-400">Modified</span>{employee.modified ? new Date(employee.modified).toLocaleString() : '-'}</div>
          </div>
        )}

        {!isNew && (
          <div className="px-6 pb-6">
            <ActivityLog
              doctype="Employee"
              docname={employee?.name || employeeName || ''}
              creationDate={employee?.creation}
              createdBy={employee?.owner}
              compact={false}
              initialVisible={5}
              collapsible
              startCollapsed
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default EmployeeDetail;
