import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { Pencil, Plus, Search, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { bankLogo, fmt, useDB, type Employee } from "@/lib/store";

export const Route = createFileRoute("/app/wafanyakazi")({
  component: EmployeesPage,
});

const empty: Omit<Employee, "id"> = {
  employeeId: "",
  userId: "",
  fullName: "",
  position: "",
  department: "",
  phone: "",
  nationalId: "",
  bankName: "CRDB",
  bankAccount: "",
  basicSalary: 0,
  taxCode: "",
  active: true,
  joinedAt: new Date().toISOString().slice(0, 10),
};

function EmployeesPage() {
  const { db, update, newId } = useDB();
  const [q, setQ] = useState("");
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState<Employee | (Omit<Employee, "id"> & { id?: string })>(empty);

  if (!db) return null;

  const list = db.employees.filter((e) =>
    [e.fullName, e.employeeId, e.department, e.position, e.phone]
      .join(" ")
      .toLowerCase()
      .includes(q.toLowerCase()),
  );

  const set = (k: string, v: string | number | boolean) => setForm((f) => ({ ...f, [k]: v }));

  function save() {
    if (!form.fullName.trim() || !form.employeeId.trim()) {
      toast.error("Weka angalau Jina kamili na Employee ID.");
      return;
    }
    update((d) => {
      const employees = form.id
        ? d.employees.map((e) => (e.id === form.id ? ({ ...form, id: form.id } as Employee) : e))
        : [...d.employees, { ...(form as Employee), id: newId() }];
      return { ...d, employees };
    });
    toast.success("Taarifa za mfanyakazi zimehifadhiwa.");
    setOpen(false);
    setForm(empty);
  }

  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-extrabold">Employee Management</h1>
          <p className="text-sm text-muted-foreground">Taarifa binafsi, mishahara, benki na vitengo.</p>
        </div>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button className="brand-gradient text-primary-foreground" onClick={() => setForm(empty)}>
              <Plus className="size-4" /> Ongeza Mfanyakazi
            </Button>
          </DialogTrigger>
          <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
            <DialogHeader>
              <DialogTitle>{form.id ? "Hariri Mfanyakazi" : "Mfanyakazi Mpya"}</DialogTitle>
            </DialogHeader>
            <div className="grid gap-3 sm:grid-cols-2">
              {([
                ["employeeId", "Employee ID"],
                ["userId", "User ID"],
                ["fullName", "Jina kamili"],
                ["position", "Cheo / Position"],
                ["department", "Kitengo"],
                ["phone", "Namba ya simu"],
                ["nationalId", "Namba ya kitambulisho"],
                ["bankName", "Benki"],
                ["bankAccount", "Account ya benki"],
                ["taxCode", "Tax code"],
                ["joinedAt", "Tarehe ya kuajiriwa"],
              ] as Array<[string, string]>).map(([k, label]) => (
                <div key={k} className="space-y-1.5">
                  <Label htmlFor={k}>{label}</Label>
                  <Input
                    id={k}
                    value={String((form as Record<string, unknown>)[k] ?? "")}
                    onChange={(e) => set(k, e.target.value)}
                  />
                </div>
              ))}

              <div className="space-y-1.5">
                <Label htmlFor="basicSalary">Basic salary</Label>
                <Input
                  id="basicSalary"
                  type="number"
                  value={form.basicSalary}
                  onChange={(e) => set("basicSalary", Number(e.target.value))}
                />
              </div>
            </div>
            <Button className="brand-gradient text-primary-foreground" onClick={save}>
              Hifadhi
            </Button>
          </DialogContent>
        </Dialog>
      </div>

      <div className="relative">
        <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
        <Input
          value={q}
          onChange={(e) => setQ(e.target.value)}
          placeholder="Tafuta kwa jina, ID, kitengo au simu..."
          className="h-11 rounded-xl pl-10"
        />
      </div>

      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
        {list.map((e) => (
          <Card key={e.id} className="card-shadow">
            <CardContent className="space-y-3 p-5">
              <div className="flex items-start justify-between gap-2">
                <div className="min-w-0">
                  <p className="truncate font-bold">{e.fullName}</p>
                  <p className="text-xs text-muted-foreground">
                    {e.position} · {e.department}
                  </p>
                </div>
                <Badge variant="secondary">{e.employeeId}</Badge>
              </div>
              <div className="grid grid-cols-2 gap-2 text-xs text-muted-foreground">
                <p>Simu: {e.phone}</p>
                <p>User ID: {e.userId}</p>
                <p className="col-span-2">Kitambulisho: {e.nationalId}</p>
              </div>
              <div className="flex items-center gap-2 rounded-xl bg-muted p-2">
                <img
                  src={bankLogo(e.bankName)}
                  alt={`Nembo ya benki ${e.bankName}`}
                  className="size-8 rounded-md bg-card object-contain"
                  loading="lazy"
                />
                <div className="text-xs">
                  <p className="font-semibold">{e.bankName}</p>
                  <p className="text-muted-foreground">{e.bankAccount}</p>
                </div>
              </div>
              <p className="text-sm font-extrabold text-primary">
                {fmt(e.basicSalary, db.settings.currency)}
              </p>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setForm(e);
                    setOpen(true);
                  }}
                >
                  <Pencil className="size-4" /> Hariri
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  className="text-destructive"
                  onClick={() => {
                    update((d) => ({ ...d, employees: d.employees.filter((x) => x.id !== e.id) }));
                    toast.success("Mfanyakazi ameondolewa.");
                  }}
                >
                  <Trash2 className="size-4" /> Futa
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}
