import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { accounting } from "@/lib/accountingClient";
import { useCompanyId } from "./lib/useCompanyId";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Plus, MoreHorizontal, Pencil, Copy, Trash2, PieChart, ArrowRight, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { TableSkeleton } from "./components/TableSkeleton";
import { EmptyState } from "./components/EmptyState";

const YEAR_OPTIONS = Array.from({ length: 7 }, (_, i) => new Date().getFullYear() - 2 + i);

export default function AccountingBudgetsPage({ basePath = "/dashboard/accounting/budgets" }: { basePath?: string } = {}) {
  const { companyId, loading: companyLoading, error: companyError, associationId } = useCompanyId();
  const cid = companyId ?? "";
  const qc = useQueryClient();
  const navigate = useNavigate();
  const goToBudget = (id: string) => navigate(`${basePath}/${id}`);

  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [fiscalYear, setFiscalYear] = useState(String(new Date().getFullYear()));
  const [periodType, setPeriodType] = useState<"monthly" | "quarterly" | "annually">("monthly");
  const [entryType, setEntryType] = useState<"account" | "customer_project">("account");
  const [prefill, setPrefill] = useState<"none" | "actuals" | "last_budget">("none");
  const [saving, setSaving] = useState(false);

  const { data: budgets = [], isLoading } = useQuery({
    queryKey: ["budgets", cid],
    enabled: !!cid,
    queryFn: async () => (await accounting.from("budgets")
      .select("*").eq("company_id", cid)
      .order("created_at", { ascending: false })).data ?? [],
  });

  const resetForm = () => {
    setName(""); setFiscalYear(String(new Date().getFullYear()));
    setPeriodType("monthly"); setEntryType("account"); setPrefill("none");
  };

  const create = async () => {
    if (!name.trim()) return toast.error("Budget name is required");
    setSaving(true);
    const { data, error } = await accounting.from("budgets").insert({
      company_id: cid,
      name: name.trim(),
      fiscal_year: parseInt(fiscalYear, 10),
      period_type: periodType,
      entry_type: entryType,
      status: "draft",
      prefill_source: prefill === "none" ? null : prefill,
    }).select().single();
    setSaving(false);
    if (error || !data) return toast.error(error?.message ?? "Failed to create budget");
    toast.success("Budget created");
    setOpen(false);
    resetForm();
    qc.invalidateQueries({ queryKey: ["budgets", cid] });
    goToBudget(data.id);
  };

  const remove = async (id: string) => {
    if (!confirm("Delete this budget?")) return;
    const { error } = await accounting.from("budgets").delete().eq("id", id);
    if (error) return toast.error(error.message);
    toast.success("Budget deleted");
    qc.invalidateQueries({ queryKey: ["budgets", cid] });
  };

  const copy = async (b: any) => {
    const { data: newB, error } = await accounting.from("budgets").insert({
      company_id: cid, name: `${b.name} (copy)`, fiscal_year: b.fiscal_year,
      period_type: b.period_type, entry_type: b.entry_type, status: "draft",
      prefill_source: b.prefill_source,
    }).select().single();
    if (error || !newB) return toast.error(error?.message ?? "Failed to copy");
    const { data: entries } = await accounting.from("budget_entries")
      .select("account_id,period_index,amount").eq("budget_id", b.id);
    if (entries?.length) {
      await accounting.from("budget_entries").insert(entries.map((e: any) => ({ ...e, budget_id: newB.id })));
    }
    toast.success("Budget copied");
    qc.invalidateQueries({ queryKey: ["budgets", cid] });
  };

  if (!associationId) return <p className="text-sm text-muted-foreground">Select an association.</p>;
  if (companyLoading) return <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>;
  if (companyError || !companyId) return <p className="text-sm text-muted-foreground text-center py-12">{companyError || "Accounting setup is not ready."}</p>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold">Budgets</h1>
          <p className="text-sm text-muted-foreground">Plan revenue and expense targets across fiscal periods.</p>
        </div>
        <Button onClick={() => { resetForm(); setOpen(true); }}>
          <Plus className="mr-1 h-4 w-4" /> New Budget
        </Button>
      </div>

      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <TableSkeleton columns={5} />
          ) : (budgets as any[]).length === 0 ? (
            <EmptyState
              icon={PieChart}
              title="No budgets yet"
              description="Create your first budget to start tracking actuals against planned figures."
              action={<Button onClick={() => { resetForm(); setOpen(true); }}><Plus className="mr-1 h-4 w-4" /> New Budget</Button>}
            />
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Fiscal Year</TableHead>
                  <TableHead>Period</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead></TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {(budgets as any[]).map((b: any) => (
                  <TableRow key={b.id} className="cursor-pointer" onClick={() => goToBudget(b.id)}>
                    <TableCell className="font-medium">
                      <span className="hover:underline font-medium">{b.name}</span>
                    </TableCell>
                    <TableCell>{b.fiscal_year}</TableCell>
                    <TableCell className="text-sm text-muted-foreground capitalize">{b.period_type}</TableCell>
                    <TableCell>
                      <Badge variant={b.status === "active" ? "default" : "secondary"}
                        className={b.status === "active" ? "bg-primary" : ""}>
                        {b.status}
                      </Badge>
                    </TableCell>
                    <TableCell onClick={(e) => e.stopPropagation()}>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button size="icon" variant="ghost"><MoreHorizontal className="h-4 w-4" /></Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={() => goToBudget(b.id)}>
                            <Pencil className="mr-2 h-4 w-4" /> Open
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => copy(b)}>
                            <Copy className="mr-2 h-4 w-4" /> Copy
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => remove(b.id)} className="text-destructive">
                            <Trash2 className="mr-2 h-4 w-4" /> Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* New Budget Dialog */}
      <Dialog open={open} onOpenChange={(v) => { setOpen(v); if (!v) resetForm(); }}>
        <DialogContent className="max-w-lg">
          <DialogHeader><DialogTitle>New Budget</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Budget name *</Label>
              <Input
                placeholder="e.g. FY 2026 Operating Budget"
                value={name}
                onChange={(e) => setName(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && create()}
                autoFocus
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Fiscal year</Label>
                <Select value={fiscalYear} onValueChange={setFiscalYear}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {YEAR_OPTIONS.map((y) => <SelectItem key={y} value={String(y)}>{y}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>Period type</Label>
                <Select value={periodType} onValueChange={(v) => setPeriodType(v as any)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="monthly">Monthly (12 periods)</SelectItem>
                    <SelectItem value="quarterly">Quarterly (4 periods)</SelectItem>
                    <SelectItem value="annually">Annual (1 period)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div>
              <Label className="mb-1 block">Pre-fill from</Label>
              <RadioGroup value={prefill} onValueChange={(v) => setPrefill(v as any)} className="flex gap-4">
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <RadioGroupItem value="none" id="p-none" /> Start empty
                </label>
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <RadioGroupItem value="actuals" id="p-actuals" /> Prior year actuals
                </label>
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <RadioGroupItem value="last_budget" id="p-last" /> Last budget
                </label>
              </RadioGroup>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
            <Button onClick={create} disabled={saving || !name.trim()}>
              {saving ? "Creating…" : <>Create <ArrowRight className="ml-1 h-4 w-4" /></>}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
