import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { KeyRound, Mail, Save, ShieldCheck, SlidersHorizontal, Trash2, UserCog } from "lucide-react";
import { toast } from "sonner";

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { changePassword, getCredentials } from "@/lib/auth";
import { clearData, useDB, type ClearScope, type Settings } from "@/lib/store";

export const Route = createFileRoute("/app/mipangilio")({
  head: () => ({
    meta: [
      { title: "Mipangilio | SmartHR Payroll Manager" },
      { name: "description", content: "Weka kiwango cha overtime, kodi, adhabu, email ya admin na nenosiri." },
      { property: "og:title", content: "Mipangilio | SmartHR Payroll Manager" },
      { property: "og:description", content: "Salary rules, akaunti ya admin na mipangilio ya mfumo." },
    ],
  }),
  component: SettingsPage,
});

const FIELDS: Array<[keyof Settings, string, "number" | "text"]> = [
  ["overtimeRate", "Kiwango cha overtime kwa saa", "number"],
  ["taxPercent", "Kodi (%)", "number"],
  ["penaltyPerLate", "Adhabu ya kuchelewa", "number"],
  ["workingDays", "Siku za kazi kwa mwezi", "number"],
  ["currency", "Sarafu", "text"],
];

function SettingsPage() {
  const { db, update } = useDB();
  const [form, setForm] = useState<Settings | null>(null);
  const [email, setEmail] = useState<string | null>(null);
  const [pw, setPw] = useState({ current: "", next: "", confirm: "" });
  const [pwError, setPwError] = useState("");

  if (!db) return null;
  const value = form ?? db.settings;
  const emailValue = email ?? db.settings.adminEmail ?? "";

  function saveRules() {
    update((d) => ({ ...d, settings: { ...d.settings, ...value, adminEmail: d.settings.adminEmail } }));
    toast.success("Salary rules zimehifadhiwa.");
  }

  function saveEmail() {
    const v = emailValue.trim();
    if (v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) {
      toast.error("Email si sahihi. Mfano: jina@mfano.com");
      return;
    }
    update((d) => ({ ...d, settings: { ...d.settings, adminEmail: v } }));
    toast.success(v ? "Email ya admin imehifadhiwa." : "Email ya admin imeondolewa.");
  }

  function savePassword(e: React.FormEvent) {
    e.preventDefault();
    setPwError("");
    const res = changePassword(pw.current, pw.next, pw.confirm);
    if (!res.ok) {
      setPwError(res.error);
      return;
    }
    setPw({ current: "", next: "", confirm: "" });
    toast.success("Nenosiri limebadilishwa kikamilifu.");
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl font-extrabold sm:text-2xl">Mipangilio ya Mfumo</h1>
        <p className="text-sm text-muted-foreground">
          Salary rules, akaunti ya admin na urejeshaji wa nenosiri.
        </p>
      </div>

      <div className="grid gap-5 xl:grid-cols-5">
        <Card className="card-shadow xl:col-span-3">
          <CardHeader className="flex flex-row items-start gap-3">
            <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-secondary text-primary">
              <SlidersHorizontal className="size-5" />
            </span>
            <div>
              <CardTitle className="text-base">Salary Rules</CardTitle>
              <CardDescription>Vigezo vinavyotumika kwenye hesabu za payroll.</CardDescription>
            </div>
          </CardHeader>
          <CardContent className="grid gap-3 sm:grid-cols-2">
            {FIELDS.map(([key, label, type]) => (
              <div key={key} className="space-y-1.5">
                <Label htmlFor={key}>{label}</Label>
                <Input
                  id={key}
                  type={type}
                  className="h-11 rounded-xl"
                  value={String(value[key] ?? "")}
                  onChange={(e) =>
                    setForm({
                      ...value,
                      [key]: type === "number" ? Number(e.target.value) : e.target.value,
                    })
                  }
                />
              </div>
            ))}
            <Button className="h-11 rounded-xl brand-gradient text-primary-foreground sm:col-span-2" onClick={saveRules}>
              <Save className="size-4" /> Hifadhi Salary Rules
            </Button>
          </CardContent>
        </Card>

        <div className="space-y-5 xl:col-span-2">
          <Card className="card-shadow">
            <CardHeader className="flex flex-row items-start gap-3">
              <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-info/10 text-info">
                <Mail className="size-5" />
              </span>
              <div>
                <CardTitle className="text-base">Email ya Admin</CardTitle>
                <CardDescription>
                  Ukisahau nenosiri, msimbo wa kubadilisha utatumwa kwenye email hii.
                </CardDescription>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="space-y-1.5">
                <Label htmlFor="adminEmail">Anwani ya email</Label>
                <Input
                  id="adminEmail"
                  type="email"
                  placeholder="mfano@wamakinda.co.tz"
                  className="h-11 rounded-xl"
                  value={emailValue}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </div>
              <Button className="h-11 w-full rounded-xl" variant="outline" onClick={saveEmail}>
                <Save className="size-4" /> Hifadhi Email
              </Button>
            </CardContent>
          </Card>

          <Card className="card-shadow">
            <CardHeader className="flex flex-row items-start gap-3">
              <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-secondary text-primary">
                <UserCog className="size-5" />
              </span>
              <div>
                <CardTitle className="text-base">Akaunti ya Admin</CardTitle>
                <CardDescription>
                  Jina la mtumiaji: <span className="font-semibold text-foreground">{getCredentials().user}</span>
                </CardDescription>
              </div>
            </CardHeader>
            <CardContent>
              <form onSubmit={savePassword} className="space-y-3">
                {(
                  [
                    ["current", "Nenosiri la sasa", "current-password"],
                    ["next", "Nenosiri jipya", "new-password"],
                    ["confirm", "Thibitisha nenosiri jipya", "new-password"],
                  ] as const
                ).map(([k, label, ac]) => (
                  <div key={k} className="space-y-1.5">
                    <Label htmlFor={`pw-${k}`}>{label}</Label>
                    <div className="relative">
                      <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-primary" />
                      <Input
                        id={`pw-${k}`}
                        type="password"
                        autoComplete={ac}
                        className="h-11 rounded-xl pl-10"
                        value={pw[k]}
                        onChange={(e) => setPw({ ...pw, [k]: e.target.value })}
                      />
                    </div>
                  </div>
                ))}
                {pwError && (
                  <p role="alert" className="rounded-xl border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm font-semibold text-destructive">
                    {pwError}
                  </p>
                )}
                <Button type="submit" className="h-11 w-full rounded-xl brand-gradient text-primary-foreground">
                  <ShieldCheck className="size-4" /> Badilisha Nenosiri
                </Button>
              </form>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
