"use client";

import { useState } from "react";
import {
  useBudgets,
  useDeleteBudget,
  useDeleteBudgetLine,
  type BudgetLineWithSpending,
} from "@/hooks/use-budgets";
import { BudgetDialog } from "@/components/budgets/BudgetDialog";
import { BudgetLineDialog } from "@/components/budgets/BudgetLineDialog";
import { formatCents, formatMonth } from "@/lib/utils/format";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Plus, Trash2, Target, Pencil } from "lucide-react";
import { CategoryIcon } from "@/components/ui/category-icon";
import { cn } from "@/lib/utils";

function progressColor(pct: number) {
  if (pct >= 100) return "bg-red-500";
  if (pct >= 80) return "bg-amber-500";
  return "bg-emerald-500";
}

function EnvelopeCard({
  line,
  budgetId,
  onEdit,
}: {
  line: BudgetLineWithSpending;
  budgetId: string;
  onEdit: (line: BudgetLineWithSpending) => void;
}) {
  const delLine = useDeleteBudgetLine();
  const remaining = line.allocatedCents - line.spentCents;
  const pct = Math.min(line.percentUsed, 100);

  return (
    <div className="p-4 rounded-lg bg-slate-800/50 border border-slate-700/50 space-y-3 group relative">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <CategoryIcon icon={line.category.icon} color={line.category.color} className="h-4 w-4 shrink-0" />
          <span className="text-sm font-medium text-slate-200">{line.category.name}</span>
          {line.percentUsed >= 100 && (
            <Badge className="text-xs bg-red-500/20 text-red-400 border-red-500/30">Over budget</Badge>
          )}
          {line.percentUsed >= 80 && line.percentUsed < 100 && (
            <Badge className="text-xs bg-amber-500/20 text-amber-400 border-amber-500/30">Near limit</Badge>
          )}
        </div>
        <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          <Button
            size="icon"
            variant="ghost"
            className="h-6 w-6 text-slate-400 hover:text-white"
            onClick={() => onEdit(line)}
          >
            <Pencil className="h-3 w-3" />
          </Button>
          <Button
            size="icon"
            variant="ghost"
            className="h-6 w-6 text-slate-400 hover:text-red-400"
            onClick={() => delLine.mutate({ budgetId, lineId: line.id })}
          >
            <Trash2 className="h-3 w-3" />
          </Button>
        </div>
      </div>

      <div className="space-y-1">
        <div className="relative h-2 w-full overflow-hidden rounded-full bg-slate-700">
          <div
            className={cn("h-full transition-all rounded-full", progressColor(line.percentUsed))}
            style={{ width: `${pct}%` }}
          />
        </div>
        <div className="flex justify-between text-xs text-slate-400">
          <span>{formatCents(line.spentCents)} spent</span>
          <span className={remaining < 0 ? "text-red-400" : "text-slate-400"}>
            {remaining >= 0 ? `${formatCents(remaining)} left` : `${formatCents(-remaining)} over`}
          </span>
          <span>{formatCents(line.allocatedCents)} budget</span>
        </div>
      </div>
    </div>
  );
}

export default function BudgetsPage() {
  const { data: budgets = [], isLoading } = useBudgets();
  const delBudget = useDeleteBudget();
  const [budgetDialogOpen, setBudgetDialogOpen] = useState(false);
  const [lineDialogOpen, setLineDialogOpen] = useState(false);
  const [activeBudgetId, setActiveBudgetId] = useState<string | null>(null);
  const [editingLine, setEditingLine] = useState<BudgetLineWithSpending | undefined>();

  const now = new Date();

  function openAddLine(budgetId: string) {
    setActiveBudgetId(budgetId);
    setEditingLine(undefined);
    setLineDialogOpen(true);
  }

  function openEditLine(budgetId: string, line: BudgetLineWithSpending) {
    setActiveBudgetId(budgetId);
    setEditingLine(line);
    setLineDialogOpen(true);
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Budgets</h1>
          <p className="text-slate-400 mt-1">
            {formatMonth(now.getMonth() + 1, now.getFullYear())} — envelope budgeting
          </p>
        </div>
        <Button
          onClick={() => setBudgetDialogOpen(true)}
          className="bg-emerald-600 hover:bg-emerald-500 text-white"
        >
          <Plus className="h-4 w-4 mr-2" />
          New Budget
        </Button>
      </div>

      {isLoading ? (
        <div className="space-y-4">
          {[1, 2].map((i) => (
            <div key={i} className="h-64 rounded-xl bg-slate-800/50 animate-pulse" />
          ))}
        </div>
      ) : budgets.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-64 rounded-xl border border-dashed border-slate-700 text-slate-500 space-y-4">
          <Target className="h-10 w-10 opacity-30" />
          <p>No budgets yet. Create one and add category envelopes.</p>
          <Button
            onClick={() => setBudgetDialogOpen(true)}
            variant="outline"
            className="border-slate-600 text-slate-300"
          >
            <Plus className="h-4 w-4 mr-2" /> Create Budget
          </Button>
        </div>
      ) : (
        <div className="space-y-6">
          {budgets.map((budget) => {
            const totalAllocated = budget.lines.reduce((s, l) => s + l.allocatedCents, 0);
            const totalSpent = budget.lines.reduce((s, l) => s + l.spentCents, 0);

            return (
              <Card key={budget.id} className="bg-slate-800/30 border-slate-700/50">
                <CardHeader className="flex flex-row items-center justify-between pb-4">
                  <div>
                    <CardTitle className="text-white text-lg">{budget.name}</CardTitle>
                    <p className="text-slate-400 text-sm mt-0.5">
                      {formatMonth(budget.startMonth, budget.startYear)}
                      {budget.isRolling && " · Rolling"}
                    </p>
                  </div>
                  <div className="flex items-center gap-3">
                    <div className="text-right">
                      <p className="text-sm text-slate-400">
                        {formatCents(totalSpent)} / {formatCents(totalAllocated)}
                      </p>
                      <p className="text-xs text-slate-500">
                        {formatCents(totalAllocated - totalSpent)} remaining
                      </p>
                    </div>
                    <div className="flex gap-1">
                      <Button
                        size="sm"
                        variant="outline"
                        className="border-slate-600 text-slate-300 hover:text-white"
                        onClick={() => openAddLine(budget.id)}
                      >
                        <Plus className="h-3.5 w-3.5 mr-1" />
                        Add envelope
                      </Button>
                      <Button
                        size="icon"
                        variant="ghost"
                        className="h-8 w-8 text-slate-500 hover:text-red-400"
                        onClick={() => {
                          if (confirm("Delete this budget and all its envelopes?")) {
                            delBudget.mutate(budget.id);
                          }
                        }}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  {budget.lines.length === 0 ? (
                    <div className="text-center py-8 text-slate-500">
                      <p className="text-sm">No envelopes yet.</p>
                      <Button
                        variant="link"
                        className="text-emerald-400 mt-1"
                        onClick={() => openAddLine(budget.id)}
                      >
                        Add first envelope
                      </Button>
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
                      {budget.lines.map((line) => (
                        <EnvelopeCard
                          key={line.id}
                          line={line}
                          budgetId={budget.id}
                          onEdit={(l) => openEditLine(budget.id, l)}
                        />
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      <BudgetDialog open={budgetDialogOpen} onClose={() => setBudgetDialogOpen(false)} />

      {activeBudgetId && (
        <BudgetLineDialog
          open={lineDialogOpen}
          onClose={() => setLineDialogOpen(false)}
          budgetId={activeBudgetId}
          existing={editingLine}
        />
      )}
    </div>
  );
}
