import React, { useEffect, useState, useCallback } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Plus, Trash2, Pencil, Eye } from "lucide-react";
import { toast } from "sonner";
import { api } from "@/lib/api";
import { useCompany } from "@/context/CompanyContext";
import { useAuth } from "@/context/AuthContext";
import { formatINR, formatDate } from "@/lib/format";
import { safeDelete } from "@/lib/safeDelete";

/**
 * Expenses (list page) — v12.34
 *
 * The small popup dialog has been REPLACED by a full-page entry screen at
 *   /expenses/new       → create
 *   /expenses/:id/edit  → edit
 *
 * This page is now PURE list + summary + per-row actions, exactly like the
 * Sales Invoices list works. All existing endpoints, schema fields, RBAC
 * rules, and the trash/restore flow remain unchanged.
 */
export default function Expenses() {
    const navigate = useNavigate();
    const { activeId } = useCompany();
    const { isAdmin } = useAuth();
    const [rows, setRows] = useState([]);
    const [searchParams, setSearchParams] = useSearchParams();

    // Legacy convenience — keep the ?new=1 dashboard shortcut working
    useEffect(() => {
        if (searchParams.get("new") === "1" || searchParams.get("income") === "1") {
            const params = searchParams.get("income") === "1" ? "?type=income" : "";
            searchParams.delete("new"); searchParams.delete("income");
            setSearchParams(searchParams, { replace: true });
            navigate(`/expenses/new${params}`);
        }
    }, [searchParams, setSearchParams, navigate]);

    const load = useCallback(async () => {
        if (!activeId) return;
        try {
            const { data } = await api.get("/expenses", { params: { company_id: activeId } });
            setRows(data || []);
        } catch (e) {
            if (!e?.isOffline && !e?.silent) toast.error("Could not load expenses");
        }
    }, [activeId]);
    useEffect(() => { load(); }, [load]);

    const remove = async (row) => {
        await safeDelete("expense", row, { onSuccess: load });
    };

    const total = rows.reduce((s, r) => s + Number(r.amount || 0), 0);

    return (
        <div className="space-y-6" data-testid="expenses-page">
            <div className="flex flex-wrap items-end justify-between gap-3">
                <div>
                    <div className="label-cap">Accounting</div>
                    <h1 className="font-display text-3xl font-bold tracking-tight">Expenses</h1>
                    <p className="text-sm text-muted-foreground mt-1">Rent, utilities, salaries and other business spends.</p>
                </div>
                {isAdmin ? (
                    <Button asChild className="bg-primary hover:bg-primary/90" data-testid="add-expense-button">
                        <Link to="/expenses/new"><Plus className="h-4 w-4 mr-1.5" /> Add Expense</Link>
                    </Button>
                ) : (
                    <span className="text-xs text-muted-foreground" data-testid="add-expense-disabled">
                        Only admins can add expenses
                    </span>
                )}
            </div>

            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                <Card><CardContent className="p-5">
                    <div className="label-cap">Total Expenses</div>
                    <div className="mt-2 font-display text-3xl font-bold num text-rose-600 dark:text-rose-400">{formatINR(total)}</div>
                </CardContent></Card>
                <Card><CardContent className="p-5">
                    <div className="label-cap">Entries</div>
                    <div className="mt-2 font-display text-3xl font-bold num">{rows.length}</div>
                </CardContent></Card>
                <Card><CardContent className="p-5">
                    <div className="label-cap">Avg / entry</div>
                    <div className="mt-2 font-display text-3xl font-bold num">{formatINR(rows.length ? total / rows.length : 0)}</div>
                </CardContent></Card>
            </div>

            <Card><CardContent className="p-0">
                <div className="overflow-x-auto">
                    <table className="w-full dense-table text-sm" data-testid="expenses-table">
                        <thead className="bg-muted/40">
                            <tr className="text-left text-[10px] tracking-wider uppercase text-muted-foreground">
                                <th className="px-5 py-2.5">Date</th>
                                <th>Category</th>
                                <th>Vendor</th>
                                <th>Payment</th>
                                <th>Notes</th>
                                <th className="text-right">Amount</th>
                                {isAdmin ? <th className="text-right pr-5">Actions</th> : <th className="text-right pr-5">View</th>}
                            </tr>
                        </thead>
                        <tbody>
                            {rows.length === 0 ? (
                                <tr><td colSpan={7} className="p-12 text-center text-muted-foreground">
                                    No expenses yet. <Link to="/expenses/new" className="text-primary underline">Add your first expense</Link>.
                                </td></tr>
                            ) : rows.map((r) => (
                                <tr key={r.id} className="border-t border-border hover:bg-muted/20">
                                    <td className="px-5 text-xs text-muted-foreground">{formatDate(r.date)}</td>
                                    <td><span className="text-xs px-2 py-0.5 rounded bg-secondary">{r.category}</span></td>
                                    <td>{r.vendor || "—"}</td>
                                    <td className="text-xs">{r.payment_mode}</td>
                                    <td className="text-xs text-muted-foreground truncate max-w-[200px]">{r.notes || "—"}</td>
                                    <td className="text-right num font-medium text-rose-600 dark:text-rose-400">{formatINR(r.amount)}</td>
                                    {isAdmin ? (
                                        <td className="text-right pr-5 whitespace-nowrap">
                                            <Button asChild size="icon" variant="ghost" className="h-8 w-8" data-testid={`edit-expense-${r.id}`}>
                                                <Link to={`/expenses/${r.id}/edit`}><Pencil className="h-3.5 w-3.5" /></Link>
                                            </Button>
                                            <Button size="icon" variant="ghost" className="h-8 w-8 text-destructive" onClick={() => remove(r)} data-testid={`delete-expense-${r.id}`}>
                                                <Trash2 className="h-3.5 w-3.5" />
                                            </Button>
                                        </td>
                                    ) : (
                                        // Non-admins see the SAME full-page expense format — in read-only mode
                                        <td className="text-right pr-5 whitespace-nowrap">
                                            <Button asChild size="icon" variant="ghost" className="h-8 w-8" data-testid={`view-expense-${r.id}`} title="View (read-only)">
                                                <Link to={`/expenses/${r.id}/edit`}><Eye className="h-3.5 w-3.5" /></Link>
                                            </Button>
                                        </td>
                                    )}
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </CardContent></Card>
        </div>
    );
}
