'use client';
import { useState, useEffect } from 'react';
import HRLayout from '../../../components/HRLayout';
import EmployeeTable from './EmployeeTable';
import AddEmployeeModal from './AddEmployeeModal';
import ViewEmployeeModal from './ViewEmployeeModal';
import EditEmployeeModal from './EditEmployeeModal';
import DeleteConfirmModal from './DeleteConfirmModal';
import ExportDropdown from './ExportDropdown';
import { useAuth } from '../../../lib/authContext';
import { fetchAllEmployees, fetchDepartments } from '../../../lib/admin-api';

export type Employee = {
  id: string;        // This is the UUID from the database
  employeeNumber: string;  // This is UF001, UF002, etc.
  name: string;
  dept: string;
  role: string;
  status: string;
  joined: string;
  salary: string;
  email: string;
  phone: string;
  dob: string;
  nationalId: string;
  kraPin: string;
  employmentType: string;
  avatar: string;
};

const DEFAULT_DEPARTMENTS = [
  'Monitoring & Evaluation', 'Transport', 'Procurement',
  'Corporate Communication', 'ICT', 'Finance', 'HR', 'Operations'
];

export let DEPARTMENTS: string[] = [...DEFAULT_DEPARTMENTS];
export const STATUSES = ['Active', 'On Leave', 'Probation', 'Inactive'];
export const EMPLOYMENT_TYPES = ['Permanent', 'Contract', 'Intern', 'Casual'];

export type EmployeesContentProps = { disableLayout?: boolean };

function mapDbEmployee(row: Record<string, unknown>): Employee {
  const salary = row.salary as number | null;
  const fullName = (row.fullName as string) || '';
  const initials = fullName
    .split(' ')
    .map(n => n[0] || '')
    .join('')
    .toUpperCase()
    .slice(0, 2);
  return {
    id: row.id as string,
    employeeNumber: row.employeeNumber as string,
    name: fullName,
    dept: row.dept as string,
    role: row.position as string,
    status: (row.isActive as boolean) ? 'Active' : 'Inactive',
    joined: ((row.joinDate as string) || '').split('T')[0],
    salary: salary ? `KES ${salary.toLocaleString()}` : 'N/A',
    email: row.email as string,
    phone: (row.phone as string) || '',
    dob: ((row.dob as string) || '').split('T')[0],
    nationalId: (row.nationalId as string) || '',
    kraPin: (row.kraPin as string) || '',
    employmentType: row.employmentType as string,
    avatar: initials || fullName.slice(0, 2).toUpperCase(),
  };
}

export default function EmployeesContent({ disableLayout }: EmployeesContentProps = {}) {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [dbLoading, setDbLoading] = useState(true);
  const [deptList, setDeptList] = useState<string[]>(DEFAULT_DEPARTMENTS);
  const [search, setSearch] = useState('');
  const [deptFilter, setDeptFilter] = useState('All');
  const [showAdd, setShowAdd] = useState(false);
  const [viewEmp, setViewEmp] = useState<Employee | null>(null);
  const [editEmp, setEditEmp] = useState<Employee | null>(null);
  const [deleteEmp, setDeleteEmp] = useState<Employee | null>(null);
  const [showExport, setShowExport] = useState(false);
  const [toast, setToast] = useState('');
  const [toastType, setToastType] = useState<'success' | 'error'>('success');
  const { user } = useAuth();
  const isHR = user?.role === 'hr';

  const loadData = async () => {
    try {
      setDbLoading(true);
      const [empRows, deptRows] = await Promise.all([
        fetchAllEmployees(),
        fetchDepartments().catch(() => [] as Record<string, unknown>[]),
      ]);
      setEmployees((empRows as Record<string, unknown>[]).map(mapDbEmployee));
      if (deptRows && deptRows.length > 0) {
        const names = (deptRows as Record<string, unknown>[]).map(d => d.name as string);
        DEPARTMENTS = names;
        setDeptList(names);
      }
    } catch (error) {
      console.error('Error loading data:', error);
      showToast('Failed to load employees. Please refresh the page.', 'error');
    } finally {
      setDbLoading(false);
    }
  };

  useEffect(() => { loadData(); }, []);

  const depts = ['All', ...deptList];

  const filtered = employees.filter(e =>
    e && e.name &&
    (deptFilter === 'All' || e.dept === deptFilter) &&
    (
      e.name.toLowerCase().includes(search.toLowerCase()) ||
      e.employeeNumber.toLowerCase().includes(search.toLowerCase()) ||
      e.email.toLowerCase().includes(search.toLowerCase())
    )
  );

  const showToast = (msg: string, type: 'success' | 'error' = 'success') => {
    setToast(msg);
    setToastType(type);
    setTimeout(() => setToast(''), 3000);
  };

  const handleAdd = async () => {
    await loadData();
    setShowAdd(false);
    showToast('Employee added successfully!', 'success');
  };

  const handleEdit = async (updated: Employee) => {
    try {
      const salaryNum = updated.salary && updated.salary !== 'N/A'
        ? parseFloat(updated.salary.replace(/[^0-9.]/g, ''))
        : null;
      const response = await fetch(`/api/admin/employees/${updated.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fullName: updated.name,
          email: updated.email,
          phone: updated.phone,
          dept: updated.dept,
          position: updated.role,
          employmentType: updated.employmentType,
          isActive: updated.status === 'Active',
          salary: salaryNum,
          dob: updated.dob || undefined,
          nationalId: updated.nationalId || undefined,
          kraPin: updated.kraPin || undefined,
        }),
      });
      if (!response.ok) throw new Error('Failed to update employee');
      setEmployees(prev => prev.map(e => e.id === updated.id ? updated : e));
      setEditEmp(null);
      showToast('Employee updated successfully!', 'success');
    } catch (error) {
      console.error('Error updating employee:', error);
      showToast('Failed to update employee', 'error');
    }
  };

  const handleDelete = async (employeeId: string) => {
    try {
      console.log('Deleting employee with ID:', employeeId);
      
      const response = await fetch(`/api/admin/employees/${employeeId}`, {
        method: 'DELETE',
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to remove employee');
      }
      
      // Remove from local state
      setEmployees(prev => prev.filter(e => e.id !== employeeId));
      setDeleteEmp(null);
      
      // Show success toast (green)
      showToast('Employee removed successfully!', 'success');
    } catch (error) {
      console.error('Error removing employee:', error);
      showToast(error instanceof Error ? error.message : 'Failed to remove employee', 'error');
    }
  };

  if (dbLoading) {
    return (
      <HRLayout title="Employee Management" breadcrumb="HR" plain={disableLayout}>
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="w-12 h-12 border-4 border-gray-200 border-t-pink-600 rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-gray-500">Loading employees...</p>
          </div>
        </div>
      </HRLayout>
    );
  }

  return (
    <HRLayout title="Employee Management" breadcrumb="HR" plain={disableLayout}>
      {/* Toast Notification */}
      {toast && (
        <div className={`fixed top-20 right-6 z-[100] text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2 ${
          toastType === 'success' ? 'bg-green-600' : 'bg-red-600'
        }`}>
          <div className="w-5 h-5 flex items-center justify-center">
            <i className={`${toastType === 'success' ? 'ri-checkbox-circle-line' : 'ri-error-warning-line'} text-lg`}></i>
          </div>
          <span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="flex flex-col gap-3 mb-5">
        <div className="flex gap-2 flex-wrap">
          {depts.map(d => (
            <button
              key={d}
              onClick={() => setDeptFilter(d)}
              className={`px-3 py-1.5 rounded-full text-xs lg:text-sm font-medium cursor-pointer whitespace-nowrap transition-all ${deptFilter === d ? 'text-white' : 'bg-white text-gray-600 border border-gray-200 hover:border-pink-300'}`}
              style={deptFilter === d ? { background: '#b828a0' } : {}}
            >
              {d}
            </button>
          ))}
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          <div className="relative flex-1 min-w-[160px]">
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Search employees..."
              className="bg-white border border-gray-200 rounded-lg px-4 py-2 text-sm w-full outline-none focus:ring-2 focus:ring-pink-300 pr-8"
            />
            <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>

          <button
            onClick={() => setShowAdd(true)}
            className="flex items-center gap-2 text-white px-4 py-2 rounded-lg text-sm font-medium cursor-pointer whitespace-nowrap"
            style={{ background: '#b828a0' }}
          >
            <i className="ri-user-add-line"></i>
            <span className="hidden sm:inline">Add Employee</span>
            <span className="sm:hidden">Add</span>
          </button>

          <div className="relative">
            <button
              onClick={() => setShowExport(v => !v)}
              className="flex items-center gap-2 bg-white border border-gray-200 text-gray-600 px-4 py-2 rounded-lg text-sm font-medium hover:bg-gray-50 cursor-pointer whitespace-nowrap"
            >
              <i className="ri-download-line"></i>
              <span className="hidden sm:inline">Export ({filtered.length})</span>
              <i className="ri-arrow-down-s-line text-xs"></i>
            </button>
            {showExport && <ExportDropdown employees={filtered} onClose={() => setShowExport(false)} />}
          </div>
        </div>
      </div>

      <EmployeeTable
        employees={filtered}
        total={employees.length}
        onView={setViewEmp}
        onEdit={setEditEmp}
        onDelete={setDeleteEmp}
      />

      {showAdd && (
        <AddEmployeeModal
          employees={employees}
          onSave={handleAdd}
          onClose={() => setShowAdd(false)}
        />
      )}

      {viewEmp && (
        <ViewEmployeeModal
          employee={viewEmp}
          onClose={() => setViewEmp(null)}
          onEdit={(e) => { setViewEmp(null); setEditEmp(e); }}
        />
      )}

      {editEmp && (
        <EditEmployeeModal
          employee={editEmp}
          onSave={handleEdit}
          onClose={() => setEditEmp(null)}
        />
      )}

      {deleteEmp && (
        <DeleteConfirmModal
          employee={deleteEmp}
          onConfirm={() => handleDelete(deleteEmp.id)}
          onClose={() => setDeleteEmp(null)}
        />
      )}
    </HRLayout>
  );
}