import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { AlertTriangle, Paperclip, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { fmt, useDB } from "@/lib/store";

export const Route = createFileRoute("/app/makosa")({
  head: () => ({
    meta: [
      { title: "Makosa | SmartHR Payroll Manager" },
      { name: "description", content: "Rekodi makosa ya wafanyakazi, adhabu na ambatisha ushahidi." },
      { property: "og:title", content: "Makosa | SmartHR Payroll Manager" },
      { property: "og:description", content: "Usimamizi wa nidhamu na adhabu za wafanyakazi." },
    ],
  }),
  component: MisconductPage,
});

function MisconductPage() {
  const { db, update, newId } = useDB();
  const [employeeId, setEmployeeId] = useState("");
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [penalty, setPenalty] = useState(0);
  const [date, setDate] = useState(new Date().toISOString().slice(0, 10));
  const [file, setFile] = useState<{ fileName: string; fileData: string } | null>(null);

  if (!db) return null;

  function onFile(f: File | undefined) {
    if (!f) return;
    const reader = new FileReader();
    reader.onload = () => setFile({ fileName: f.name, fileData: String(reader.result) });
    reader.readAsDataURL(f);
  }

  function save() {
    if (!employeeId || !title.trim()) {
      toast.error("Chagua mfanyakazi na weka kichwa cha kosa.");
      return;
    }
    update((d) => ({
      ...d,
      misconducts: [
        ...d.misconducts,
        { id: newId(), employeeId, date, title, description, penalty, ...(file ?? {}) },
      ],
    }));
    toast.success("Kosa limerekodiwa.");
    setTitle("");
    setDescription("");
    setPenalty(0);
    setFile(null);
  }

  return (
    <div className="space-y-5">
      <div>
        <h1 className="text-xl font-extrabold">Misconduct Management</h1>
        <p className="text-sm text-muted-foreground">Rekodi makosa, adhabu na ushahidi. Adhabu hukatwa kwenye payroll.</p>
      </div>

      <Card className="card-shadow">
        <CardHeader>
          <CardTitle className="text-base">Rekodi Kosa Jipya</CardTitle>
        </CardHeader>
        <CardContent className="grid gap-3 sm:grid-cols-2">
          <div className="space-y-1.5">
            <Label htmlFor="emp">Mfanyakazi</Label>
            <select
              id="emp"
              value={employeeId}
              onChange={(e) => setEmployeeId(e.target.value)}
              className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
            >
              <option value="">-- Chagua --</option>
              {db.employees.map((e) => (
                <option key={e.id} value={e.employeeId}>
                  {e.fullName} ({e.employeeId})
                </option>
              ))}
            </select>
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="date">Tarehe</Label>
            <Input id="date" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="title">Kichwa cha kosa</Label>
            <Input id="title" value={title} onChange={(e) => setTitle(e.target.value)} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="penalty">Adhabu (kiasi)</Label>
            <Input id="penalty" type="number" value={penalty} onChange={(e) => setPenalty(Number(e.target.value))} />
          </div>
          <div className="space-y-1.5 sm:col-span-2">
            <Label htmlFor="desc">Maelezo</Label>
            <Input id="desc" value={description} onChange={(e) => setDescription(e.target.value)} />
          </div>
          <div className="space-y-1.5 sm:col-span-2">
            <Label htmlFor="file">Ambatisha ushahidi</Label>
            <Input id="file" type="file" onChange={(e) => onFile(e.target.files?.[0])} />
            {file && <p className="text-xs text-muted-foreground">{file.fileName}</p>}
          </div>
          <Button className="brand-gradient text-primary-foreground sm:col-span-2" onClick={save}>
            Hifadhi Kosa
          </Button>
        </CardContent>
      </Card>

      <div className="grid gap-4 md:grid-cols-2">
        {db.misconducts.map((m) => (
          <Card key={m.id} className="card-shadow">
            <CardContent className="space-y-2 p-5">
              <div className="flex items-start justify-between gap-2">
                <div>
                  <p className="flex items-center gap-2 font-bold">
                    <AlertTriangle className="size-4 text-destructive" /> {m.title}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {db.employees.find((e) => e.employeeId === m.employeeId)?.fullName ?? m.employeeId} · {m.date}
                  </p>
                </div>
                <Badge variant="secondary">{fmt(m.penalty, db.settings.currency)}</Badge>
              </div>
              <p className="text-sm text-muted-foreground">{m.description}</p>
              {m.fileName && (
                <a href={m.fileData} download={m.fileName} className="flex items-center gap-1 text-xs text-primary underline">
                  <Paperclip className="size-3" /> {m.fileName}
                </a>
              )}
              <Button
                variant="outline"
                size="sm"
                className="text-destructive"
                onClick={() => {
                  update((d) => ({ ...d, misconducts: d.misconducts.filter((x) => x.id !== m.id) }));
                  toast.success("Kosa limefutwa.");
                }}
              >
                <Trash2 className="size-4" /> Futa
              </Button>
            </CardContent>
          </Card>
        ))}
        {!db.misconducts.length && <p className="text-sm text-muted-foreground">Hakuna makosa yaliyorekodiwa.</p>}
      </div>
    </div>
  );
}
