"use client";
import { useState } from "react";
import { Plus, Search, Edit3, Trash2, UserCheck, UserX, Phone, Mail, Hash } from "lucide-react";
import Avatar from "./ui/Avatar";
import Badge from "./ui/Badge";
import Modal from "./ui/Modal";
import EmployeeProfileModal from "./EmployeeProfileModal";
import { AVATAR_COLORS } from "@/lib/utils";

interface Employee {
  id: number;
  firstName: string;
  lastName: string;
  rank: string | null;
  role: "admin" | "supervisor" | "officer";
  orgNodeId: number | null;
  departmentId: number | null;
  avatarColor: string | null;
  badgeNumber: string | null;
  email: string | null;
  phone: string | null;
  hireDate: string | null;
  isActive: boolean | null;
}

interface OrgNode {
  id: number;
  name: string;
  type: string;
  color: string | null;
}

interface EmployeeManagerProps {
  employees: Employee[];
  orgNodes: OrgNode[];
  departmentId: number;
  onUpdate: () => void;
  actorId?: number | null;
}

const RANKS = ["Chief", "Deputy Chief", "Captain", "Lieutenant", "Sergeant", "Corporal", "Officer", "Detective", "Recruit"];
const ROLES = ["admin", "supervisor", "officer"] as const;

const ROLE_COLORS: Record<string, string> = {
  admin: "#EF4444",
  supervisor: "#F59E0B",
  officer: "#3B82F6",
};

const emptyEmployee: {
  firstName: string;
  lastName: string;
  badgeNumber: string;
  rank: string;
  role: "admin" | "supervisor" | "officer";
  orgNodeId: number | null;
  email: string;
  phone: string;
  hireDate: string;
  avatarColor: string;
  isActive: boolean;
} = {
  firstName: "",
  lastName: "",
  badgeNumber: "",
  rank: "Officer",
  role: "officer",
  orgNodeId: null,
  email: "",
  phone: "",
  hireDate: "",
  avatarColor: AVATAR_COLORS[0],
  isActive: true,
};

export default function EmployeeManager({ employees, orgNodes, departmentId, onUpdate, actorId = null }: EmployeeManagerProps) {
  const [profileId, setProfileId] = useState<number | null>(null);
  const [search, setSearch] = useState("");
  const [filterNode, setFilterNode] = useState<number | null>(null);
  const [filterActive, setFilterActive] = useState<boolean | null>(true);
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState<Employee | null>(null);
  const [form, setForm] = useState<typeof emptyEmployee>({ ...emptyEmployee });
  const [saving, setSaving] = useState(false);

  const filtered = employees.filter((e) => {
    const matchSearch = search.trim() === "" ||
      `${e.firstName} ${e.lastName} ${e.badgeNumber ?? ""} ${e.rank ?? ""}`.toLowerCase().includes(search.toLowerCase());
    const matchNode = !filterNode || e.orgNodeId === filterNode;
    const matchActive = filterActive === null || e.isActive === filterActive;
    return matchSearch && matchNode && matchActive;
  });

  const openAdd = () => {
    setEditing(null);
    setForm({ ...emptyEmployee });
    setShowModal(true);
  };

  const openEdit = (emp: Employee) => {
    setEditing(emp);
    setForm({
      firstName: emp.firstName,
      lastName: emp.lastName,
      badgeNumber: emp.badgeNumber ?? "",
      rank: emp.rank ?? "Officer",
      role: emp.role as "admin" | "supervisor" | "officer",
      orgNodeId: emp.orgNodeId,
      email: emp.email ?? "",
      phone: emp.phone ?? "",
      hireDate: emp.hireDate ?? "",
      avatarColor: emp.avatarColor ?? AVATAR_COLORS[0],
      isActive: emp.isActive ?? true,
    });
    setShowModal(true);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const payload = {
        ...form,
        departmentId,
        orgNodeId: form.orgNodeId || null,
        badgeNumber: form.badgeNumber || null,
        email: form.email || null,
        phone: form.phone || null,
        hireDate: form.hireDate || null,
      };
      if (editing) {
        await fetch("/api/employees", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ ...payload, id: editing.id }),
        });
      } else {
        await fetch("/api/employees", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        });
      }
      setShowModal(false);
      onUpdate();
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (emp: Employee) => {
    if (!confirm(`Deactivate ${emp.firstName} ${emp.lastName}?`)) return;
    await fetch(`/api/employees?id=${emp.id}`, { method: "DELETE" });
    onUpdate();
  };

  const handleReactivate = async (emp: Employee) => {
    await fetch("/api/employees", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...emp, isActive: true }),
    });
    onUpdate();
  };

  return (
    <div>
      {/* Filters */}
      <div className="flex flex-wrap gap-3 mb-5">
        <div className="flex-1 min-w-[200px] relative">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search by name, badge, rank..."
            className="w-full pl-9 pr-4 py-2 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
        <select
          value={filterNode ?? ""}
          onChange={(e) => setFilterNode(e.target.value ? parseInt(e.target.value) : null)}
          className="border border-slate-200 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="">All Units</option>
          {orgNodes.map((n) => <option key={n.id} value={n.id}>{n.name}</option>)}
        </select>
        <select
          value={filterActive === null ? "" : filterActive ? "true" : "false"}
          onChange={(e) => setFilterActive(e.target.value === "" ? null : e.target.value === "true")}
          className="border border-slate-200 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="true">Active</option>
          <option value="false">Inactive</option>
          <option value="">All</option>
        </select>
        <button
          onClick={openAdd}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-medium hover:bg-blue-700 transition-colors"
        >
          <Plus size={16} />
          Add Officer
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-4 mb-5">
        <div className="bg-blue-50 rounded-xl p-4">
          <div className="text-2xl font-bold text-blue-600">{employees.filter((e) => e.isActive).length}</div>
          <div className="text-xs text-slate-500">Active Officers</div>
        </div>
        <div className="bg-amber-50 rounded-xl p-4">
          <div className="text-2xl font-bold text-amber-600">{employees.filter((e) => e.role === "supervisor" && e.isActive).length}</div>
          <div className="text-xs text-slate-500">Supervisors</div>
        </div>
        <div className="bg-slate-50 rounded-xl p-4">
          <div className="text-2xl font-bold text-slate-600">{orgNodes.length}</div>
          <div className="text-xs text-slate-500">Units</div>
        </div>
      </div>

      {/* Employee List */}
      <div className="space-y-2">
        {filtered.length === 0 && (
          <div className="text-center py-12 text-slate-400">
            <p className="text-lg font-medium">No officers found</p>
            <p className="text-sm mt-1">Try adjusting filters or add a new officer</p>
          </div>
        )}
        {filtered.map((emp) => {
          const node = orgNodes.find((n) => n.id === emp.orgNodeId);
          return (
            <div
              key={emp.id}
              className="flex items-center gap-4 p-4 bg-white rounded-xl border border-slate-200 hover:shadow-sm transition-all group"
            >
              <button
                onClick={() => setProfileId(emp.id)}
                title="Open full profile"
                className="hover:ring-2 hover:ring-blue-400 rounded-full transition-all flex-shrink-0"
              >
                <Avatar
                  firstName={emp.firstName}
                  lastName={emp.lastName}
                  color={emp.avatarColor ?? "#3B82F6"}
                  size="md"
                />
              </button>
              <div className="flex-1 min-w-0 cursor-pointer" onClick={() => setProfileId(emp.id)}>
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="font-semibold text-slate-800">
                    {emp.firstName} {emp.lastName}
                  </span>
                  {!emp.isActive && (
                    <Badge color="#94A3B8">Inactive</Badge>
                  )}
                  <Badge color={ROLE_COLORS[emp.role] ?? "#3B82F6"}>{emp.role}</Badge>
                </div>
                <div className="flex items-center gap-4 mt-1 flex-wrap">
                  {emp.rank && <span className="text-sm text-slate-500">{emp.rank}</span>}
                  {emp.badgeNumber && (
                    <span className="text-xs text-slate-400 flex items-center gap-1">
                      <Hash size={11} />#{emp.badgeNumber}
                    </span>
                  )}
                  {emp.email && (
                    <span className="text-xs text-slate-400 flex items-center gap-1">
                      <Mail size={11} />{emp.email}
                    </span>
                  )}
                  {emp.phone && (
                    <span className="text-xs text-slate-400 flex items-center gap-1">
                      <Phone size={11} />{emp.phone}
                    </span>
                  )}
                </div>
                {node && (
                  <div className="mt-1">
                    <Badge color={node.color ?? "#3B82F6"}>{node.name}</Badge>
                  </div>
                )}
              </div>
              <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                {!emp.isActive ? (
                  <button
                    onClick={() => handleReactivate(emp)}
                    className="p-2 rounded-xl bg-green-50 text-green-500 hover:bg-green-100 transition-colors"
                    title="Reactivate"
                  >
                    <UserCheck size={16} />
                  </button>
                ) : (
                  <button
                    onClick={() => handleDelete(emp)}
                    className="p-2 rounded-xl bg-red-50 text-red-400 hover:bg-red-100 transition-colors"
                    title="Deactivate"
                  >
                    <UserX size={16} />
                  </button>
                )}
                <button
                  onClick={() => openEdit(emp)}
                  className="p-2 rounded-xl bg-slate-50 text-slate-500 hover:bg-slate-100 transition-colors"
                  title="Edit"
                >
                  <Edit3 size={16} />
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {/* Add/Edit Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title={editing ? "Edit Officer" : "Add New Officer"}
        size="lg"
      >
        <div className="space-y-4">
          {/* Avatar color picker */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">Avatar Color</label>
            <div className="flex gap-2 flex-wrap">
              {AVATAR_COLORS.map((c) => (
                <button
                  key={c}
                  onClick={() => setForm({ ...form, avatarColor: c })}
                  className={`w-8 h-8 rounded-full transition-all ${form.avatarColor === c ? "ring-2 ring-offset-2 ring-blue-500 scale-110" : ""}`}
                  style={{ backgroundColor: c }}
                />
              ))}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">First Name *</label>
              <input
                type="text"
                value={form.firstName}
                onChange={(e) => setForm({ ...form, firstName: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Last Name *</label>
              <input
                type="text"
                value={form.lastName}
                onChange={(e) => setForm({ ...form, lastName: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Badge Number</label>
              <input
                type="text"
                value={form.badgeNumber}
                onChange={(e) => setForm({ ...form, badgeNumber: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Hire Date</label>
              <input
                type="date"
                value={form.hireDate}
                onChange={(e) => setForm({ ...form, hireDate: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Rank</label>
              <select
                value={form.rank}
                onChange={(e) => setForm({ ...form, rank: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {RANKS.map((r) => <option key={r} value={r}>{r}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Role</label>
              <select
                value={form.role}
                onChange={(e) => setForm({ ...form, role: e.target.value as typeof ROLES[number] })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {ROLES.map((r) => <option key={r} value={r}>{r.charAt(0).toUpperCase() + r.slice(1)}</option>)}
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Assigned Unit</label>
            <select
              value={form.orgNodeId ?? ""}
              onChange={(e) => setForm({ ...form, orgNodeId: e.target.value ? parseInt(e.target.value) : null })}
              className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Unassigned</option>
              {orgNodes.map((n) => <option key={n.id} value={n.id}>{n.name} ({n.type})</option>)}
            </select>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Email</label>
              <input
                type="email"
                value={form.email}
                onChange={(e) => setForm({ ...form, email: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Phone</label>
              <input
                type="tel"
                value={form.phone}
                onChange={(e) => setForm({ ...form, phone: e.target.value })}
                className="w-full border border-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          <div className="flex gap-3 pt-2">
            <button
              onClick={handleSave}
              disabled={saving || !form.firstName || !form.lastName}
              className="flex-1 py-2.5 bg-blue-600 text-white rounded-xl font-medium hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              {saving ? "Saving..." : editing ? "Save Changes" : "Add Officer"}
            </button>
            <button
              onClick={() => setShowModal(false)}
              className="px-4 py-2.5 border border-slate-200 rounded-xl text-slate-600 hover:bg-slate-50 transition-colors"
            >
              Cancel
            </button>
          </div>
        </div>
      </Modal>

      <EmployeeProfileModal
        employeeId={profileId}
        actorId={actorId}
        onClose={() => setProfileId(null)}
        onSaved={onUpdate}
      />
    </div>
  );
}
