"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft, Plus, Pencil, Trash2, Search, MoreHorizontal } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import {
  useCategories,
  useToggleCategory,
  useCreateCategory,
  useUpdateCategory,
  useDeleteCategory,
  type CategoryWithPref,
} from "@/hooks/use-categories";
import { cn } from "@/lib/utils";
import { ICON_MAP } from "@/components/ui/category-icon";

// ── Constants ─────────────────────────────────────────────────────────────────

const BILLING_LABEL: Record<string, string> = {
  NONE: "One-time", MONTHLY: "Monthly", QUARTERLY: "Quarterly", ANNUAL: "Annual",
};
const BILLING_COLOR: Record<string, string> = {
  NONE: "", MONTHLY: "text-blue-400", QUARTERLY: "text-amber-400", ANNUAL: "text-violet-400",
};
const BILLING_BG: Record<string, string> = {
  NONE: "", MONTHLY: "bg-blue-500/10", QUARTERLY: "bg-amber-500/10", ANNUAL: "bg-violet-500/10",
};

const PRESET_COLORS = [
  "#f97316","#fb923c","#eab308","#22c55e","#10b981","#06b6d4",
  "#3b82f6","#8b5cf6","#d946ef","#ec4899","#ef4444","#e11d48",
  "#22d3ee","#6366f1","#a78bfa","#64748b",
];

const PRESET_ICONS = Object.keys(ICON_MAP);

type BillingCycle = "NONE" | "MONTHLY" | "QUARTERLY" | "ANNUAL";

interface FormState {
  name: string;
  type: "EXPENSE" | "INCOME";
  icon: string;
  color: string;
  billingCycle: BillingCycle;
}
const EMPTY: FormState = {
  name: "", type: "EXPENSE", icon: "more-horizontal",
  color: "#6366f1", billingCycle: "NONE",
};

// ── Page ──────────────────────────────────────────────────────────────────────

export default function CategoriesSettingsPage() {
  const router                = useRouter();
  const { data: cats = [], isLoading } = useCategories();
  const toggle  = useToggleCategory();
  const create  = useCreateCategory();
  const update  = useUpdateCategory();
  const remove  = useDeleteCategory();

  const [tab,        setTab]        = useState<"EXPENSE" | "INCOME">("EXPENSE");
  const [search,     setSearch]     = useState("");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing,    setEditing]    = useState<CategoryWithPref | null>(null);
  const [form,       setForm]       = useState<FormState>(EMPTY);
  const [deleteId,   setDeleteId]   = useState<string | null>(null);

  const byTab = cats.filter((c) => c.type === tab);
  const shown = search.trim()
    ? byTab.filter((c) => c.name.toLowerCase().includes(search.toLowerCase()))
    : byTab;

  const periodic = shown.filter((c) => c.billingCycle && c.billingCycle !== "NONE");
  const regular  = shown.filter((c) => !c.billingCycle || c.billingCycle === "NONE");

  function openAdd() {
    setEditing(null);
    setForm({ ...EMPTY, type: tab });
    setDialogOpen(true);
  }
  function openEdit(cat: CategoryWithPref) {
    setEditing(cat);
    setForm({
      name:         cat.name,
      type:         cat.type as "EXPENSE" | "INCOME",
      icon:         cat.icon ?? "more-horizontal",
      color:        cat.color ?? "#6366f1",
      billingCycle: (cat.billingCycle ?? "NONE") as BillingCycle,
    });
    setDialogOpen(true);
  }
  async function handleSave() {
    if (!form.name.trim()) return;
    if (editing) {
      await update.mutateAsync({ id: editing.id, data: { name: form.name, icon: form.icon, color: form.color, billingCycle: form.billingCycle } });
    } else {
      await create.mutateAsync(form);
    }
    setDialogOpen(false);
  }
  async function confirmDelete() {
    if (!deleteId) return;
    await remove.mutateAsync(deleteId);
    setDeleteId(null);
  }

  const enabledCount   = byTab.filter((c) => c.isEnabled !== false).length;
  const periodicCount  = byTab.filter((c) => c.billingCycle && c.billingCycle !== "NONE").length;

  return (
    <div className="space-y-6 max-w-2xl">

      {/* Header */}
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.back()}
          className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800 transition-colors"
        >
          <ArrowLeft className="h-4 w-4" />
        </button>
        <div className="flex-1 min-w-0">
          <h1 className="text-2xl font-bold text-white">Categories</h1>
          <p className="text-slate-400 text-sm mt-0.5">
            {cats.length} total · {enabledCount} active · {periodicCount} recurring bills
          </p>
        </div>
        <Button onClick={openAdd} className="bg-emerald-600 hover:bg-emerald-500 text-white shrink-0">
          <Plus className="h-4 w-4 mr-1.5" /> Add
        </Button>
      </div>

      {/* Type tabs + search */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="flex gap-1 p-1 bg-slate-800 rounded-xl w-fit">
          {(["EXPENSE", "INCOME"] as const).map((t) => (
            <button
              key={t}
              onClick={() => setTab(t)}
              className={cn(
                "px-5 py-2 rounded-lg text-sm font-semibold transition-all",
                tab === t ? "bg-slate-700 text-white shadow" : "text-slate-400 hover:text-slate-200"
              )}
            >
              {t === "EXPENSE" ? "Expenses" : "Income"}
              <span className="ml-1.5 text-[10px] opacity-60">
                ({cats.filter(c => c.type === t).length})
              </span>
            </button>
          ))}
        </div>

        <div className="relative flex-1 max-w-xs">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-slate-500 pointer-events-none" />
          <Input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search categories…"
            className="pl-8 h-9 bg-slate-800 border-slate-700 text-white placeholder:text-slate-500 text-sm"
          />
        </div>
      </div>

      {/* Category lists */}
      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 10 }).map((_, i) => (
            <div key={i} className="h-[68px] bg-slate-800/30 rounded-2xl animate-pulse" />
          ))}
        </div>
      ) : shown.length === 0 ? (
        <div className="text-center py-16 text-slate-500 text-sm">
          {search ? `No categories match "${search}"` : "No categories yet"}
        </div>
      ) : (
        <div className="space-y-6">

          {/* Recurring Bills */}
          {periodic.length > 0 && (
            <section className="space-y-2">
              <div className="flex items-center gap-2 px-1">
                <p className="text-[10px] text-slate-500 uppercase tracking-widest font-semibold">
                  Recurring Bills
                </p>
                <div className="flex-1 h-px bg-slate-800" />
                <span className="text-[10px] text-slate-600">{periodic.length}</span>
              </div>
              <div className="space-y-2">
                {periodic.map((cat) => (
                  <CategoryRow
                    key={cat.id}
                    cat={cat}
                    onToggle={() => toggle.mutate({ id: cat.id, isEnabled: !cat.isEnabled })}
                    onEdit={() => openEdit(cat)}
                    onDelete={() => setDeleteId(cat.id)}
                  />
                ))}
              </div>
            </section>
          )}

          {/* Regular / Other */}
          {regular.length > 0 && (
            <section className="space-y-2">
              <div className="flex items-center gap-2 px-1">
                <p className="text-[10px] text-slate-500 uppercase tracking-widest font-semibold">
                  {periodic.length > 0 ? "Other Categories" : "All Categories"}
                </p>
                <div className="flex-1 h-px bg-slate-800" />
                <span className="text-[10px] text-slate-600">{regular.length}</span>
              </div>
              <div className="space-y-2">
                {regular.map((cat) => (
                  <CategoryRow
                    key={cat.id}
                    cat={cat}
                    onToggle={() => toggle.mutate({ id: cat.id, isEnabled: !cat.isEnabled })}
                    onEdit={() => openEdit(cat)}
                    onDelete={() => setDeleteId(cat.id)}
                  />
                ))}
              </div>
            </section>
          )}
        </div>
      )}

      {/* ── Add / Edit dialog ───────────────────────────────────────────────── */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="bg-slate-900 border-slate-700 text-white max-w-md">
          <DialogHeader>
            <DialogTitle className="text-lg">
              {editing ? "Edit Category" : "New Category"}
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-5 mt-1">
            {/* Preview */}
            <div className="flex items-center gap-4 p-4 rounded-2xl border border-slate-700/50 bg-slate-800/50">
              <div
                className="w-12 h-12 rounded-2xl flex items-center justify-center shrink-0"
                style={{ backgroundColor: `${form.color}25` }}
              >
                {(() => {
                  const Icon = ICON_MAP[form.icon] ?? MoreHorizontal;
                  return <Icon className="h-5 w-5" style={{ color: form.color }} />;
                })()}
              </div>
              <div>
                <p className="font-semibold text-white">{form.name || "Category name"}</p>
                <p className="text-xs text-slate-400 mt-0.5">
                  {form.type} · {BILLING_LABEL[form.billingCycle]}
                </p>
              </div>
            </div>

            {/* Name */}
            <div className="space-y-1.5">
              <Label className="text-slate-300 text-xs uppercase tracking-wide">Name</Label>
              <Input
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                placeholder="e.g. Gym Membership"
                className="bg-slate-800 border-slate-600 text-white placeholder:text-slate-500"
              />
            </div>

            {/* Type — only for new */}
            {!editing && (
              <div className="space-y-1.5">
                <Label className="text-slate-300 text-xs uppercase tracking-wide">Type</Label>
                <div className="flex gap-2">
                  {(["EXPENSE", "INCOME"] as const).map((t) => (
                    <button
                      key={t}
                      type="button"
                      onClick={() => setForm((f) => ({ ...f, type: t }))}
                      className={cn(
                        "flex-1 py-2.5 rounded-xl text-sm font-semibold border transition-all",
                        form.type === t
                          ? "bg-emerald-500/20 border-emerald-500/40 text-emerald-300"
                          : "bg-slate-800 border-slate-700 text-slate-400 hover:border-slate-600"
                      )}
                    >
                      {t === "EXPENSE" ? "Expense" : "Income"}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Billing cycle */}
            <div className="space-y-1.5">
              <Label className="text-slate-300 text-xs uppercase tracking-wide">Billing Cycle</Label>
              <div className="grid grid-cols-4 gap-2">
                {(["NONE", "MONTHLY", "QUARTERLY", "ANNUAL"] as const).map((b) => (
                  <button
                    key={b}
                    type="button"
                    onClick={() => setForm((f) => ({ ...f, billingCycle: b }))}
                    className={cn(
                      "py-2.5 rounded-xl text-xs font-semibold border transition-all",
                      form.billingCycle === b
                        ? "bg-blue-500/20 border-blue-500/40 text-blue-300"
                        : "bg-slate-800 border-slate-700 text-slate-400 hover:border-slate-600"
                    )}
                  >
                    {BILLING_LABEL[b]}
                  </button>
                ))}
              </div>
            </div>

            {/* Color palette */}
            <div className="space-y-1.5">
              <Label className="text-slate-300 text-xs uppercase tracking-wide">Color</Label>
              <div className="flex flex-wrap gap-2">
                {PRESET_COLORS.map((c) => (
                  <button
                    key={c}
                    type="button"
                    onClick={() => setForm((f) => ({ ...f, color: c }))}
                    className="w-8 h-8 rounded-full border-2 transition-all hover:scale-110"
                    style={{
                      backgroundColor: c,
                      borderColor: form.color === c ? "white" : "transparent",
                      boxShadow:   form.color === c ? `0 0 0 3px ${c}50` : "none",
                    }}
                  />
                ))}
              </div>
            </div>

            {/* Icon grid */}
            <div className="space-y-1.5">
              <Label className="text-slate-300 text-xs uppercase tracking-wide">Icon</Label>
              <div className="grid grid-cols-7 gap-1.5">
                {PRESET_ICONS.map((ico) => {
                  const Icon = ICON_MAP[ico] ?? MoreHorizontal;
                  const active = form.icon === ico;
                  return (
                    <button
                      key={ico}
                      type="button"
                      onClick={() => setForm((f) => ({ ...f, icon: ico }))}
                      className={cn(
                        "h-9 rounded-xl flex items-center justify-center border transition-all",
                        active
                          ? "border-transparent"
                          : "border-slate-700 bg-slate-800 hover:border-slate-600"
                      )}
                      style={active ? {
                        backgroundColor: `${form.color}25`,
                        borderColor:     `${form.color}60`,
                      } : undefined}
                    >
                      <Icon
                        className="h-4 w-4"
                        style={{ color: active ? form.color : "#64748b" }}
                      />
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Actions */}
            <div className="flex gap-3 pt-1">
              <Button
                variant="outline"
                onClick={() => setDialogOpen(false)}
                className="flex-1 border-slate-600 text-slate-300 hover:bg-slate-800"
              >
                Cancel
              </Button>
              <Button
                onClick={handleSave}
                disabled={!form.name.trim() || create.isPending || update.isPending}
                className="flex-1 bg-emerald-600 hover:bg-emerald-500 text-white"
              >
                {create.isPending || update.isPending
                  ? "Saving…"
                  : editing ? "Save Changes" : "Add Category"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* ── Delete confirm ─────────────────────────────────────────────────── */}
      <Dialog open={!!deleteId} onOpenChange={(v) => !v && setDeleteId(null)}>
        <DialogContent className="bg-slate-900 border-slate-700 text-white max-w-sm">
          <DialogHeader>
            <DialogTitle>Delete Category?</DialogTitle>
          </DialogHeader>
          <p className="text-slate-400 text-sm mt-1">
            The category will be hidden from the list. Existing transactions keep their tag.
          </p>
          <div className="flex gap-3 mt-4">
            <Button variant="outline" onClick={() => setDeleteId(null)} className="flex-1 border-slate-600 text-slate-300 hover:bg-slate-800">
              Cancel
            </Button>
            <Button onClick={confirmDelete} disabled={remove.isPending} className="flex-1 bg-red-600 hover:bg-red-500 text-white">
              {remove.isPending ? "Deleting…" : "Delete"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// ── CategoryRow ───────────────────────────────────────────────────────────────

function CategoryRow({
  cat,
  onToggle,
  onEdit,
  onDelete,
}: {
  cat: CategoryWithPref;
  onToggle: () => void;
  onEdit: () => void;
  onDelete: () => void;
}) {
  const Icon  = ICON_MAP[cat.icon ?? ""] ?? MoreHorizontal;
  const color = cat.color ?? "#64748b";
  const hasCycle = cat.billingCycle && cat.billingCycle !== "NONE";

  return (
    <div
      className={cn(
        "flex items-center gap-3 px-4 py-3 rounded-2xl border transition-all",
        cat.isEnabled
          ? "bg-slate-800/60 border-slate-700/50 hover:border-slate-600/60"
          : "bg-slate-800/20 border-slate-700/20 opacity-45"
      )}
    >
      {/* Icon */}
      <div
        className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0"
        style={{ backgroundColor: `${color}20` }}
      >
        <Icon className="h-[18px] w-[18px]" style={{ color }} />
      </div>

      {/* Name + billing badge */}
      <div className="flex-1 min-w-0">
        <p className="text-sm font-semibold text-slate-100 truncate">{cat.name}</p>
        {hasCycle ? (
          <span
            className={cn(
              "inline-block mt-0.5 text-[10px] font-semibold px-1.5 py-0.5 rounded-full",
              BILLING_BG[cat.billingCycle!],
              BILLING_COLOR[cat.billingCycle!]
            )}
          >
            {BILLING_LABEL[cat.billingCycle!]}
          </span>
        ) : (
          <p className="text-[11px] text-slate-600 mt-0.5">One-time</p>
        )}
      </div>

      {/* System badge */}
      {cat.isSystem && (
        <span className="text-[9px] px-1.5 py-0.5 rounded-md bg-slate-700/60 text-slate-500 font-medium shrink-0">
          system
        </span>
      )}

      {/* Edit / Delete — custom only */}
      {!cat.isSystem && (
        <div className="flex gap-1 shrink-0">
          <button
            onClick={onEdit}
            className="p-1.5 rounded-lg text-slate-500 hover:text-slate-200 hover:bg-slate-700 transition-colors"
          >
            <Pencil className="h-3.5 w-3.5" />
          </button>
          <button
            onClick={onDelete}
            className="p-1.5 rounded-lg text-slate-500 hover:text-red-400 hover:bg-slate-700 transition-colors"
          >
            <Trash2 className="h-3.5 w-3.5" />
          </button>
        </div>
      )}

      {/* Toggle */}
      <button
        type="button"
        onClick={onToggle}
        className={cn(
          "relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border-2 border-transparent transition-colors",
          cat.isEnabled ? "bg-emerald-600" : "bg-slate-600"
        )}
      >
        <span
          className={cn(
            "block h-4 w-4 rounded-full bg-white shadow transition-transform",
            cat.isEnabled ? "translate-x-4" : "translate-x-0"
          )}
        />
      </button>
    </div>
  );
}
