"use client";

import { useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/app-shell";
import { apiFetch } from "@/lib/api";

type Payee = {
  id: string;
  name: string;
  category?: string | null;
  accountNumberLast4?: string | null;
};

type Bill = {
  id: string;
  payeeId?: string | null;
  name: string;
  amount: string | number;
  currency: string;
  dueDate: string;
  status: "pending" | "scheduled" | "paid" | "skipped" | "cancelled";
  computedStatus: string;
  recurrence: string;
  autopay: boolean;
  reminderDays: number;
  paidAt?: string | null;
  payee?: Payee | null;
};

type BillSummary = {
  activeCount: number;
  upcomingCount: number;
  overdueCount: number;
  totalDueNext30: string;
};

const today = new Date().toISOString().slice(0, 10);

export default function BillsPage() {
  const [payees, setPayees] = useState<Payee[]>([]);
  const [bills, setBills] = useState<Bill[]>([]);
  const [summary, setSummary] = useState<BillSummary | null>(null);
  const [status, setStatus] = useState("");
  const [filter, setFilter] = useState("all");
  const [payeeForm, setPayeeForm] = useState({ name: "", category: "", accountNumberLast4: "" });
  const [billForm, setBillForm] = useState({
    payeeId: "",
    name: "",
    amount: "",
    dueDate: today,
    status: "pending",
    recurrence: "none",
    autopay: false,
    reminderDays: "3",
    notes: "",
  });

  const filteredBills = useMemo(() => {
    if (filter === "all") return bills;
    if (filter === "overdue") return bills.filter((bill) => bill.computedStatus === "overdue");
    return bills.filter((bill) => bill.status === filter);
  }, [bills, filter]);

  const money = (value: string | number, currency = "USD") =>
    new Intl.NumberFormat("en-US", { style: "currency", currency }).format(Number(value ?? 0));

  const load = async () => {
    const [payeesRes, billsRes, summaryRes] = await Promise.all([
      apiFetch<Payee[]>("/api/bill-pay/payees"),
      apiFetch<Bill[]>("/api/bill-pay/bills"),
      apiFetch<BillSummary>("/api/bill-pay/summary"),
    ]);
    if (!payeesRes.error) setPayees(payeesRes.data ?? []);
    if (!billsRes.error) setBills(billsRes.data ?? []);
    if (!summaryRes.error) setSummary(summaryRes.data ?? null);
  };

  useEffect(() => {
    load().catch(() => setStatus("Unable to load bills."));
  }, []);

  const createPayee = async () => {
    if (!payeeForm.name.trim()) {
      setStatus("Payee name is required.");
      return;
    }
    const res = await apiFetch<Payee>("/api/bill-pay/payees", {
      method: "POST",
      body: JSON.stringify(payeeForm),
    });
    if (res.error) {
      setStatus(res.error.message ?? "Unable to create payee.");
      return;
    }
    setPayeeForm({ name: "", category: "", accountNumberLast4: "" });
    setStatus("Payee created.");
    await load();
  };

  const createBill = async () => {
    if (!billForm.name.trim() || !billForm.amount || !billForm.dueDate) {
      setStatus("Bill name, amount, and due date are required.");
      return;
    }
    const payload = {
      ...billForm,
      payeeId: billForm.payeeId || undefined,
      amount: Number(billForm.amount),
      reminderDays: Number(billForm.reminderDays || 3),
    };
    const res = await apiFetch<Bill>("/api/bill-pay/bills", {
      method: "POST",
      body: JSON.stringify(payload),
    });
    if (res.error) {
      setStatus(res.error.message ?? "Unable to create bill.");
      return;
    }
    setBillForm({ payeeId: "", name: "", amount: "", dueDate: today, status: "pending", recurrence: "none", autopay: false, reminderDays: "3", notes: "" });
    setStatus("Bill created.");
    await load();
  };

  const markPaid = async (bill: Bill) => {
    const res = await apiFetch(`/api/bill-pay/bills/${bill.id}/pay`, {
      method: "POST",
      body: JSON.stringify({
        amount: Number(bill.amount),
        paidAt: new Date().toISOString(),
        method: bill.autopay ? "autopay" : "manual",
      }),
    });
    if (res.error) {
      setStatus(res.error.message ?? "Unable to mark bill paid.");
      return;
    }
    setStatus(`${bill.name} marked paid.`);
    await load();
  };

  const initiatePayment = async (bill: Bill) => {
    const res = await apiFetch(`/api/bill-pay/bills/${bill.id}/initiate-payment`, {
      method: "POST",
      body: JSON.stringify({
        amount: Number(bill.amount),
        scheduledFor: new Date().toISOString(),
        method: "ach",
        memo: `LedgerOne payment for ${bill.name}`,
      }),
    });
    if (res.error) {
      setStatus(res.error.message ?? "Unable to initiate payment.");
      return;
    }
    setStatus(`${bill.name} payment initiated.`);
    await load();
  };

  const updateStatus = async (bill: Bill, nextStatus: Bill["status"]) => {
    const res = await apiFetch(`/api/bill-pay/bills/${bill.id}`, {
      method: "PATCH",
      body: JSON.stringify({ status: nextStatus }),
    });
    if (res.error) {
      setStatus(res.error.message ?? "Unable to update bill.");
      return;
    }
    setStatus("Bill updated.");
    await load();
  };

  const inputCls = "mt-2 w-full rounded-xl border border-border bg-background/50 px-4 py-2 text-sm text-foreground focus:border-primary focus:ring-primary focus:outline-none";
  const labelCls = "text-xs text-muted-foreground font-semibold uppercase tracking-wider";

  return (
    <AppShell title="Bills" subtitle="Track payees, due dates, reminders, and recorded payments.">
      <div className="space-y-6">
        <div className="grid gap-4 md:grid-cols-4">
          <div className="rounded-xl border border-border bg-secondary/10 p-5">
            <p className="text-xs text-muted-foreground">Active bills</p>
            <p className="mt-2 text-2xl font-bold text-foreground">{summary?.activeCount ?? 0}</p>
          </div>
          <div className="rounded-xl border border-border bg-secondary/10 p-5">
            <p className="text-xs text-muted-foreground">Due next 30 days</p>
            <p className="mt-2 text-2xl font-bold text-foreground">{summary?.upcomingCount ?? 0}</p>
          </div>
          <div className="rounded-xl border border-border bg-secondary/10 p-5">
            <p className="text-xs text-muted-foreground">Overdue</p>
            <p className="mt-2 text-2xl font-bold text-foreground">{summary?.overdueCount ?? 0}</p>
          </div>
          <div className="rounded-xl border border-border bg-secondary/10 p-5">
            <p className="text-xs text-muted-foreground">Total due next 30 days</p>
            <p className="mt-2 text-2xl font-bold text-foreground">{money(summary?.totalDueNext30 ?? 0)}</p>
          </div>
        </div>

        <div className="grid gap-6 lg:grid-cols-[0.85fr_1.15fr]">
          <section className="rounded-xl border border-border bg-secondary/10 p-6">
            <p className="text-sm font-bold text-foreground">Payees</p>
            <div className="mt-4 grid gap-3">
              <div>
                <label className={labelCls}>Name</label>
                <input value={payeeForm.name} onChange={(event) => setPayeeForm((prev) => ({ ...prev, name: event.target.value }))} className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>Category</label>
                <input value={payeeForm.category} onChange={(event) => setPayeeForm((prev) => ({ ...prev, category: event.target.value }))} className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>Account last 4</label>
                <input maxLength={4} value={payeeForm.accountNumberLast4} onChange={(event) => setPayeeForm((prev) => ({ ...prev, accountNumberLast4: event.target.value }))} className={inputCls} />
              </div>
              <button onClick={createPayee} className="rounded-lg bg-primary px-4 py-2.5 text-sm font-bold text-primary-foreground hover:bg-primary/90">Add Payee</button>
            </div>
            <div className="mt-6 divide-y divide-border">
              {payees.length === 0 && <p className="py-4 text-sm text-muted-foreground">No payees yet.</p>}
              {payees.map((payee) => (
                <div key={payee.id} className="py-3">
                  <p className="text-sm font-semibold text-foreground">{payee.name}</p>
                  <p className="text-xs text-muted-foreground">{payee.category || "Uncategorized"}{payee.accountNumberLast4 ? ` · ${payee.accountNumberLast4}` : ""}</p>
                </div>
              ))}
            </div>
          </section>

          <section className="rounded-xl border border-border bg-secondary/10 p-6">
            <p className="text-sm font-bold text-foreground">New Bill</p>
            <div className="mt-4 grid gap-4 md:grid-cols-2">
              <div>
                <label className={labelCls}>Payee</label>
                <select value={billForm.payeeId} onChange={(event) => setBillForm((prev) => ({ ...prev, payeeId: event.target.value }))} className={inputCls}>
                  <option value="">No payee</option>
                  {payees.map((payee) => <option key={payee.id} value={payee.id}>{payee.name}</option>)}
                </select>
              </div>
              <div>
                <label className={labelCls}>Bill name</label>
                <input value={billForm.name} onChange={(event) => setBillForm((prev) => ({ ...prev, name: event.target.value }))} className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>Amount</label>
                <input type="number" step="0.01" value={billForm.amount} onChange={(event) => setBillForm((prev) => ({ ...prev, amount: event.target.value }))} className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>Due date</label>
                <input type="date" value={billForm.dueDate} onChange={(event) => setBillForm((prev) => ({ ...prev, dueDate: event.target.value }))} className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>Recurrence</label>
                <select value={billForm.recurrence} onChange={(event) => setBillForm((prev) => ({ ...prev, recurrence: event.target.value }))} className={inputCls}>
                  <option value="none">None</option>
                  <option value="weekly">Weekly</option>
                  <option value="monthly">Monthly</option>
                  <option value="quarterly">Quarterly</option>
                  <option value="yearly">Yearly</option>
                </select>
              </div>
              <div>
                <label className={labelCls}>Reminder days</label>
                <input type="number" min={0} max={30} value={billForm.reminderDays} onChange={(event) => setBillForm((prev) => ({ ...prev, reminderDays: event.target.value }))} className={inputCls} />
              </div>
              <label className="flex items-center gap-2 text-sm text-foreground">
                <input type="checkbox" checked={billForm.autopay} onChange={(event) => setBillForm((prev) => ({ ...prev, autopay: event.target.checked }))} className="rounded border-border text-primary focus:ring-primary" />
                Autopay enabled externally
              </label>
              <button onClick={createBill} className="rounded-lg bg-primary px-4 py-2.5 text-sm font-bold text-primary-foreground hover:bg-primary/90">Add Bill</button>
            </div>
            {status && <p className="mt-4 rounded-lg border border-border bg-background/60 px-4 py-3 text-sm text-muted-foreground">{status}</p>}
          </section>
        </div>

        <section className="rounded-xl border border-border bg-secondary/10 p-6">
          <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
            <p className="text-sm font-bold text-foreground">Bill Schedule</p>
            <select value={filter} onChange={(event) => setFilter(event.target.value)} className="rounded-lg border border-border bg-background/50 px-3 py-2 text-sm text-foreground">
              <option value="all">All</option>
              <option value="pending">Pending</option>
              <option value="scheduled">Scheduled</option>
              <option value="overdue">Overdue</option>
              <option value="paid">Paid</option>
              <option value="skipped">Skipped</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>

          <div className="mt-4 divide-y divide-border">
            {filteredBills.length === 0 && <p className="py-8 text-sm text-muted-foreground">No bills for this view.</p>}
            {filteredBills.map((bill) => (
              <article key={bill.id} className="py-4">
                <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                  <div>
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="text-sm font-bold text-foreground">{bill.name}</p>
                      <span className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">{bill.computedStatus}</span>
                      {bill.autopay && <span className="rounded-full bg-primary/10 px-2 py-0.5 text-xs text-primary">autopay</span>}
                    </div>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {money(bill.amount, bill.currency)} due {new Date(bill.dueDate).toLocaleDateString()} · {bill.recurrence}
                    </p>
                    {bill.payee && <p className="mt-1 text-xs text-muted-foreground">Payee: {bill.payee.name}</p>}
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {bill.status !== "paid" && (
                      <button onClick={() => initiatePayment(bill)} className="rounded-lg bg-primary px-3 py-2 text-xs font-bold text-primary-foreground hover:bg-primary/90">Initiate Payment</button>
                    )}
                    {bill.status !== "paid" && (
                      <button onClick={() => markPaid(bill)} className="rounded-lg border border-primary/30 px-3 py-2 text-xs font-bold text-primary hover:bg-primary/10">Mark Paid</button>
                    )}
                    {bill.status !== "skipped" && bill.status !== "paid" && (
                      <button onClick={() => updateStatus(bill, "skipped")} className="rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground hover:bg-secondary/40">Skip</button>
                    )}
                    {bill.status !== "cancelled" && bill.status !== "paid" && (
                      <button onClick={() => updateStatus(bill, "cancelled")} className="rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground hover:bg-secondary/40">Cancel</button>
                    )}
                  </div>
                </div>
              </article>
            ))}
          </div>
        </section>
      </div>
    </AppShell>
  );
}
