"use client";

import { useState } from "react";
import { Headset, Plus, Target, Trash2, Users, Wallet } from "lucide-react";
import { api, useApi } from "@/lib/client";
import { Badge, Button, Card, DataTable, Field, Input, Modal, PageHeader, StatCard, useToast, type Column } from "@/components/ui";
import { formatDate, money } from "@/lib/utils";

interface Employee extends Record<string, unknown> {
  id: number;
  employeeCode: string;
  name: string;
  phone: string | null;
  email: string | null;
  designation: string | null;
  joiningDate: string | null;
  salary: string | null;
  monthlyTarget: string | null;
  isActive: boolean;
  userName: string | null;
  customers: number;
  collection: number;
  tickets: number;
  openTickets: number;
}

const empty = { employeeCode: "", name: "", phone: "", email: "", designation: "", address: "", joiningDate: "", salary: "0", monthlyTarget: "0", isActive: true };

export default function EmployeesPage() {
  const toast = useToast();
  const { data, loading, reload } = useApi<{ items: Employee[] }>("/api/employees");
  const [modal, setModal] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [form, setForm] = useState(empty);
  const [busy, setBusy] = useState(false);

  const totalCollection = (data?.items ?? []).reduce((a, e) => a + Number(e.collection), 0);
  const totalCustomers = (data?.items ?? []).reduce((a, e) => a + Number(e.customers), 0);
  const openTickets = (data?.items ?? []).reduce((a, e) => a + Number(e.openTickets), 0);

  const columns: Column<Employee>[] = [
    { key: "employeeCode", label: "Code", render: (r) => <span className="font-mono text-xs text-slate-400">{r.employeeCode}</span> },
    {
      key: "name",
      label: "Employee",
      render: (r) => (
        <div className="min-w-0">
          <p className="truncate font-medium text-slate-100">{r.name}</p>
          <p className="text-[11px] text-slate-500">{r.designation ?? "—"}</p>
        </div>
      ),
    },
    { key: "phone", label: "Phone", hideOnMobile: true },
    { key: "customers", label: "Customers", render: (r) => <span className="font-semibold text-brand-400">{r.customers}</span> },
    { key: "collection", label: "This month", render: (r) => <span className="font-semibold text-emerald-300">{money(r.collection)}</span> },
    { key: "monthlyTarget", label: "Target", hideOnMobile: true, render: (r) => money(r.monthlyTarget) },
    { key: "openTickets", label: "Open tickets", hideOnMobile: true },
    { key: "joiningDate", label: "Joined", hideOnMobile: true, render: (r) => formatDate(r.joiningDate) },
    { key: "isActive", label: "Status", render: (r) => <Badge value={r.isActive ? "active" : "inactive"} /> },
    {
      key: "actions",
      label: "",
      render: (r) => (
        <div className="flex gap-1">
          <Button
            size="sm"
            variant="ghost"
            onClick={() => {
              setEditId(r.id);
              setForm({
                employeeCode: r.employeeCode,
                name: r.name,
                phone: r.phone ?? "",
                email: r.email ?? "",
                designation: r.designation ?? "",
                address: "",
                joiningDate: r.joiningDate ?? "",
                salary: r.salary ?? "0",
                monthlyTarget: r.monthlyTarget ?? "0",
                isActive: r.isActive,
              });
              setModal(true);
            }}
          >
            Edit
          </Button>
          <Button
            size="sm"
            variant="ghost"
            icon={<Trash2 className="h-3.5 w-3.5 text-rose-400" />}
            onClick={async () => {
              if (!confirm(`Delete ${r.name}?`)) return;
              try {
                await api(`/api/employees?id=${r.id}`, { method: "DELETE" });
                toast.push("Employee deleted", "success");
                void reload();
              } catch (err) {
                toast.push(err instanceof Error ? err.message : "Delete failed", "error");
              }
            }}
          />
        </div>
      ),
    },
  ];

  const save = async () => {
    setBusy(true);
    try {
      const payload = { ...form, id: editId ?? undefined, salary: Number(form.salary), monthlyTarget: Number(form.monthlyTarget) };
      if (editId) await api("/api/employees", { method: "PUT", json: payload });
      else await api("/api/employees", { method: "POST", json: payload });
      toast.push(editId ? "Employee updated" : "Employee added", "success");
      setModal(false);
      void reload();
    } catch (err) {
      toast.push(err instanceof Error ? err.message : "Save failed", "error");
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <PageHeader
        title="Employee management"
        subtitle="Collectors, support engineers, assignments and performance"
        icon={<Headset className="h-5 w-5" />}
        actions={
          <Button
            size="sm"
            icon={<Plus className="h-4 w-4" />}
            onClick={() => {
              setEditId(null);
              setForm(empty);
              setModal(true);
            }}
          >
            Add employee
          </Button>
        }
      />

      <div className="mb-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
        <StatCard label="Team size" value={data?.items.length ?? 0} icon={<Users className="h-5 w-5" />} tone="brand" />
        <StatCard label="Assigned customers" value={totalCustomers} icon={<Users className="h-5 w-5" />} tone="cyan" />
        <StatCard label="Collection this month" value={money(totalCollection)} icon={<Wallet className="h-5 w-5" />} tone="green" />
        <StatCard label="Open tickets" value={openTickets} icon={<Target className="h-5 w-5" />} tone="amber" />
      </div>

      <Card className="p-2">
        <DataTable columns={columns} rows={data?.items ?? []} loading={loading} rowKey={(r) => r.id} />
      </Card>

      <Modal
        open={modal}
        onClose={() => setModal(false)}
        title={editId ? "Edit employee" : "Add employee"}
        subtitle="Employees can be linked to customer assignments and ticket queues"
        footer={
          <>
            <Button variant="secondary" onClick={() => setModal(false)}>
              Cancel
            </Button>
            <Button loading={busy} onClick={() => void save()}>
              Save
            </Button>
          </>
        }
      >
        <div className="grid gap-4 sm:grid-cols-2">
          <Field label="Employee code">
            <Input value={form.employeeCode} onChange={(e) => setForm({ ...form, employeeCode: e.target.value })} placeholder="EMP-005" />
          </Field>
          <Field label="Full name">
            <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
          </Field>
          <Field label="Phone">
            <Input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
          </Field>
          <Field label="Email">
            <Input value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
          </Field>
          <Field label="Designation">
            <Input value={form.designation} onChange={(e) => setForm({ ...form, designation: e.target.value })} />
          </Field>
          <Field label="Joining date">
            <Input type="date" value={form.joiningDate} onChange={(e) => setForm({ ...form, joiningDate: e.target.value })} />
          </Field>
          <Field label="Salary">
            <Input type="number" value={form.salary} onChange={(e) => setForm({ ...form, salary: e.target.value })} />
          </Field>
          <Field label="Monthly target">
            <Input type="number" value={form.monthlyTarget} onChange={(e) => setForm({ ...form, monthlyTarget: e.target.value })} />
          </Field>
        </div>
      </Modal>
    </>
  );
}
