import { useState, useEffect, useRef } from 'react';
import {
  Title, Table, Group, Button, Stack, Text, NumberInput,
  Select, Loader, Center, Badge, Card, Alert, Modal,
} from '@mantine/core';
import { notifications } from '@mantine/notifications';
import {
  IconDeviceFloppy, IconInfoCircle, IconPencil, IconX,
  IconCheck, IconArrowBack, IconTrash, IconRefresh,
  IconUpload, IconDownload,
} from '@tabler/icons-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../services/api';
import { useIsReadOnly } from '../../stores/authStore';
import { usePreferencesStore } from '../../stores/preferencesStore';

interface PlanLine {
  id: string;
  account_id: string;
  account_number: string;
  account_name: string;
  account_type: string;
  fund_type: string;
  is_manually_adjusted: boolean;
  jan: number; feb: number; mar: number; apr: number;
  may: number; jun: number; jul: number; aug: number;
  sep: number; oct: number; nov: number; dec_amt: number;
  annual_total: number;
}

const monthKeys = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec_amt'];
const monthLabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

const fmt = (v: number) => v.toLocaleString('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 });

function hydrateLine(row: any): PlanLine {
  const line: any = { ...row };
  for (const m of monthKeys) {
    line[m] = Number(line[m]) || 0;
  }
  line.annual_total = monthKeys.reduce((sum, m) => sum + (line[m] || 0), 0);
  return line as PlanLine;
}

function parseCurrencyValue(val: string): number {
  if (!val) return 0;
  let s = val.trim();
  if (!s || s === '-' || s === '$-' || s === '$ -') return 0;
  const isNegative = s.includes('(') && s.includes(')');
  s = s.replace(/[$,\s()]/g, '');
  if (!s || s === '-') return 0;
  const num = parseFloat(s);
  if (isNaN(num)) return 0;
  return isNegative ? -num : num;
}

function parseCSV(text: string): Record<string, string>[] {
  const lines = text.trim().split('\n');
  if (lines.length < 2) return [];
  const headers = lines[0].split(',').map((h) => h.trim().toLowerCase());
  const rows: Record<string, string>[] = [];
  for (let i = 1; i < lines.length; i++) {
    const line = lines[i].trim();
    if (!line) continue;
    const values: string[] = [];
    let current = '';
    let inQuotes = false;
    for (let j = 0; j < line.length; j++) {
      const ch = line[j];
      if (ch === '"') { inQuotes = !inQuotes; }
      else if (ch === ',' && !inQuotes) { values.push(current.trim()); current = ''; }
      else { current += ch; }
    }
    values.push(current.trim());
    const row: Record<string, string> = {};
    headers.forEach((h, idx) => { row[h] = values[idx] || ''; });
    rows.push(row);
  }
  return rows;
}

const statusColors: Record<string, string> = {
  planning: 'blue',
  approved: 'yellow',
  ratified: 'green',
};

export function BudgetPlanningPage() {
  const queryClient = useQueryClient();
  const isReadOnly = useIsReadOnly();
  const isDark = usePreferencesStore((s) => s.colorScheme) === 'dark';
  const stickyBg = isDark ? 'var(--mantine-color-dark-7)' : 'white';
  const stickyBorder = isDark ? 'var(--mantine-color-dark-4)' : '#e9ecef';
  const incomeSectionBg = isDark ? 'var(--mantine-color-green-9)' : '#e6f9e6';
  const expenseSectionBg = isDark ? 'var(--mantine-color-red-9)' : '#fde8e8';

  const [selectedYear, setSelectedYear] = useState<string | null>(null);
  const [lineData, setLineData] = useState<PlanLine[]>([]);
  const [isEditing, setIsEditing] = useState(false);
  const [inflationInput, setInflationInput] = useState<number>(2.5);
  const [confirmModal, setConfirmModal] = useState<{ action: string; title: string; message: string } | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Available years
  const { data: availableYears } = useQuery<any>({
    queryKey: ['budget-plan-available-years'],
    queryFn: async () => {
      const { data } = await api.get('/board-planning/budget-plans/available-years');
      return data;
    },
  });

  // Set default year when available
  useEffect(() => {
    if (availableYears?.years?.length && !selectedYear) {
      setSelectedYear(String(availableYears.years[0].year));
    }
  }, [availableYears, selectedYear]);

  // Plan data for selected year
  const { data: plan, isLoading } = useQuery<any>({
    queryKey: ['budget-plan', selectedYear],
    queryFn: async () => {
      const { data } = await api.get(`/board-planning/budget-plans/${selectedYear}`);
      return data;
    },
    enabled: !!selectedYear,
  });

  // Hydrate lines when plan changes
  useEffect(() => {
    if (plan?.lines) {
      setLineData(plan.lines.map(hydrateLine));
      setInflationInput(parseFloat(plan.inflation_rate) || 2.5);
      setIsEditing(false);
    } else {
      setLineData([]);
    }
  }, [plan]);

  const hasBaseBudget = !!availableYears?.latestBudgetYear;

  const yearOptions = (availableYears?.years || []).map((y: any) => ({
    value: String(y.year),
    label: `${y.year}${y.hasPlan ? ` (${y.status})` : ''}`,
  }));

  // If no base budget at all, also offer the current year as an option
  const currentYear = new Date().getFullYear();
  const allYearOptions = !hasBaseBudget && !yearOptions.find((y: any) => y.value === String(currentYear))
    ? [{ value: String(currentYear), label: String(currentYear) }, ...yearOptions]
    : yearOptions;

  // Mutations
  const createMutation = useMutation({
    mutationFn: async () => {
      const fiscalYear = parseInt(selectedYear!, 10);
      const baseYear = availableYears?.latestBudgetYear || new Date().getFullYear();
      const { data } = await api.post('/board-planning/budget-plans', {
        fiscalYear,
        baseYear,
        inflationRate: inflationInput,
      });
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['budget-plan'] });
      queryClient.invalidateQueries({ queryKey: ['budget-plan-available-years'] });
      notifications.show({ message: 'Budget plan created', color: 'green' });
    },
    onError: (err: any) => {
      notifications.show({ message: err.response?.data?.message || 'Create failed', color: 'red' });
    },
  });

  const saveMutation = useMutation({
    mutationFn: async () => {
      const payload = lineData.map((l) => ({
        accountId: l.account_id,
        fundType: l.fund_type,
        jan: l.jan, feb: l.feb, mar: l.mar, apr: l.apr,
        may: l.may, jun: l.jun, jul: l.jul, aug: l.aug,
        sep: l.sep, oct: l.oct, nov: l.nov, dec: l.dec_amt,
      }));
      return api.put(`/board-planning/budget-plans/${selectedYear}/lines`, {
        planId: plan.id,
        lines: payload,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['budget-plan', selectedYear] });
      setIsEditing(false);
      notifications.show({ message: 'Budget plan saved', color: 'green' });
    },
    onError: (err: any) => {
      notifications.show({ message: err.response?.data?.message || 'Save failed', color: 'red' });
    },
  });

  const importMutation = useMutation({
    mutationFn: async (lines: Record<string, string>[]) => {
      const parsed = lines.map((row) => ({
        account_number: row.account_number || row.accountnumber || '',
        account_name: row.account_name || row.accountname || '',
        jan: parseCurrencyValue(row.jan),
        feb: parseCurrencyValue(row.feb),
        mar: parseCurrencyValue(row.mar),
        apr: parseCurrencyValue(row.apr),
        may: parseCurrencyValue(row.may),
        jun: parseCurrencyValue(row.jun),
        jul: parseCurrencyValue(row.jul),
        aug: parseCurrencyValue(row.aug),
        sep: parseCurrencyValue(row.sep),
        oct: parseCurrencyValue(row.oct),
        nov: parseCurrencyValue(row.nov),
        dec_amt: parseCurrencyValue(row.dec_amt || row.dec || ''),
      }));
      const { data } = await api.post(`/board-planning/budget-plans/${selectedYear}/import`, parsed);
      return data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['budget-plan', selectedYear] });
      queryClient.invalidateQueries({ queryKey: ['budget-plan-available-years'] });
      queryClient.invalidateQueries({ queryKey: ['accounts'] });
      let msg = `Imported ${data.imported} budget line(s)`;
      if (data.created?.length) msg += `. Created ${data.created.length} new account(s)`;
      if (data.errors?.length) msg += `. ${data.errors.length} error(s): ${data.errors.join('; ')}`;
      notifications.show({
        message: msg,
        color: data.errors?.length ? 'yellow' : 'green',
        autoClose: 10000,
      });
    },
    onError: (err: any) => {
      notifications.show({ message: err.response?.data?.message || 'Import failed', color: 'red' });
    },
  });

  const inflationMutation = useMutation({
    mutationFn: () => api.put(`/board-planning/budget-plans/${selectedYear}/inflation`, {
      inflationRate: inflationInput,
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['budget-plan', selectedYear] });
      notifications.show({ message: 'Inflation rate applied', color: 'green' });
    },
  });

  const statusMutation = useMutation({
    mutationFn: (status: string) => api.put(`/board-planning/budget-plans/${selectedYear}/status`, { status }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['budget-plan', selectedYear] });
      queryClient.invalidateQueries({ queryKey: ['budget-plan-available-years'] });
      queryClient.invalidateQueries({ queryKey: ['budgets'] });
      setConfirmModal(null);
      notifications.show({ message: 'Status updated', color: 'green' });
    },
    onError: (err: any) => {
      notifications.show({ message: err.response?.data?.message || 'Status update failed', color: 'red' });
      setConfirmModal(null);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () => api.delete(`/board-planning/budget-plans/${selectedYear}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['budget-plan', selectedYear] });
      queryClient.invalidateQueries({ queryKey: ['budget-plan-available-years'] });
      setConfirmModal(null);
      notifications.show({ message: 'Budget plan deleted', color: 'orange' });
    },
  });

  const updateCell = (idx: number, month: string, value: number) => {
    const updated = [...lineData];
    (updated[idx] as any)[month] = value || 0;
    updated[idx].annual_total = monthKeys.reduce((s, m) => s + ((updated[idx] as any)[m] || 0), 0);
    setLineData(updated);
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    queryClient.invalidateQueries({ queryKey: ['budget-plan', selectedYear] });
  };

  const handleDownloadTemplate = async () => {
    try {
      const yr = selectedYear || currentYear;
      const response = await api.get(`/board-planning/budget-plans/${yr}/template`, {
        responseType: 'blob',
      });
      const blob = new Blob([response.data], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `budget_template_${yr}.csv`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    } catch (err: any) {
      notifications.show({ message: 'Failed to download template', color: 'red' });
    }
  };

  const handleImportCSV = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      const text = e.target?.result as string;
      if (!text) { notifications.show({ message: 'Could not read file', color: 'red' }); return; }
      const rows = parseCSV(text);
      if (rows.length === 0) { notifications.show({ message: 'No data rows found in CSV', color: 'red' }); return; }
      importMutation.mutate(rows);
    };
    reader.readAsText(file);
    event.target.value = '';
  };

  const hasPlan = !!plan?.id;
  const status = plan?.status || 'planning';
  const cellsEditable = !isReadOnly && isEditing && status !== 'ratified';

  const incomeLines = lineData.filter((b) => b.account_type === 'income');
  const operatingIncomeLines = incomeLines.filter((b) => b.fund_type === 'operating');
  const reserveIncomeLines = incomeLines.filter((b) => b.fund_type === 'reserve');
  const expenseLines = lineData.filter((b) => b.account_type === 'expense');
  const totalOperatingIncome = operatingIncomeLines.reduce((sum, l) => sum + (l.annual_total || 0), 0);
  const totalReserveIncome = reserveIncomeLines.reduce((sum, l) => sum + (l.annual_total || 0), 0);
  const totalExpense = expenseLines.reduce((sum, l) => sum + (l.annual_total || 0), 0);

  return (
    <Stack>
      {/* Header */}
      <Group justify="space-between" align="flex-start">
        <Group align="center">
          <Title order={2}>Budget Planning</Title>
          {hasPlan && (
            <Badge size="lg" color={statusColors[status]}>
              {status}
            </Badge>
          )}
        </Group>
        <Group>
          <Select
            data={allYearOptions}
            value={selectedYear}
            onChange={setSelectedYear}
            w={180}
            placeholder="Select year"
          />
          <Button
            variant="outline"
            leftSection={<IconDownload size={16} />}
            onClick={handleDownloadTemplate}
            size="sm"
          >
            Download Template
          </Button>
        </Group>
      </Group>

      {/* Hidden file input for CSV import */}
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: 'none' }}
        accept=".csv,.txt"
        onChange={handleFileChange}
      />

      {isLoading && <Center h={300}><Loader /></Center>}

      {/* Empty state - no base budget exists at all */}
      {!isLoading && !hasPlan && selectedYear && !hasBaseBudget && (
        <Alert icon={<IconInfoCircle size={16} />} color="orange" variant="light">
          <Stack gap="sm">
            <Text fw={600}>No budget data found in the system</Text>
            <Text size="sm">
              To get started with budget planning, you need to load an initial budget.
              You can either create a new budget from scratch or import an existing budget from a CSV file.
            </Text>
            <Text size="sm" c="dimmed">
              Use <Text span fw={600}>Download Template</Text> above to get a CSV with your chart of accounts pre-populated,
              fill in the monthly amounts, then import it below.
            </Text>
            <Group>
              <Button
                leftSection={<IconUpload size={16} />}
                onClick={handleImportCSV}
                loading={importMutation.isPending}
              >
                Import Budget from CSV
              </Button>
              <Button
                variant="light"
                onClick={() => createMutation.mutate()}
                loading={createMutation.isPending}
              >
                Create Empty Budget Plan
              </Button>
            </Group>
          </Stack>
        </Alert>
      )}

      {/* Empty state - base budget exists but no plan for this year */}
      {!isLoading && !hasPlan && selectedYear && hasBaseBudget && (
        <Alert icon={<IconInfoCircle size={16} />} color="blue" variant="light">
          <Stack gap="sm">
            <Text>No budget plan exists for {selectedYear}. Create one based on the {availableYears?.latestBudgetYear} budget with an inflation adjustment, or import a CSV directly.</Text>
            <Group>
              <NumberInput
                label="Inflation Rate (%)"
                value={inflationInput}
                onChange={(v) => setInflationInput(Number(v) || 0)}
                min={0}
                max={50}
                step={0.5}
                decimalScale={2}
                w={160}
                size="sm"
              />
              <Button
                mt={24}
                onClick={() => createMutation.mutate()}
                loading={createMutation.isPending}
              >
                Create Budget Plan for {selectedYear}
              </Button>
              <Text mt={24} c="dimmed">or</Text>
              <Button
                mt={24}
                variant="outline"
                leftSection={<IconUpload size={16} />}
                onClick={handleImportCSV}
                loading={importMutation.isPending}
              >
                Import from CSV
              </Button>
            </Group>
            <Text size="xs" c="dimmed">
              Base year: {availableYears?.latestBudgetYear}. Each monthly amount will be compounded annually by the specified inflation rate.
            </Text>
          </Stack>
        </Alert>
      )}

      {/* Plan controls */}
      {hasPlan && (
        <>
          <Group justify="space-between">
            <Group>
              <NumberInput
                label="Inflation Rate (%)"
                value={inflationInput}
                onChange={(v) => setInflationInput(Number(v) || 0)}
                min={0}
                max={50}
                step={0.5}
                decimalScale={2}
                w={140}
                size="xs"
                disabled={status === 'ratified' || isReadOnly}
              />
              <Button
                mt={24}
                size="xs"
                variant="light"
                leftSection={<IconRefresh size={14} />}
                onClick={() => {
                  setConfirmModal({
                    action: 'inflation',
                    title: 'Apply Inflation Rate',
                    message: `This will recalculate all non-manually-adjusted lines using ${inflationInput}% inflation compounded annually from the base year (${plan.base_year}). Manually adjusted lines will be preserved.`,
                  });
                }}
                disabled={status === 'ratified' || isReadOnly}
              >
                Apply
              </Button>
              <Text size="xs" c="dimmed" mt={24}>Base year: {plan.base_year}</Text>
            </Group>

            <Group>
              {!isReadOnly && (
                <>
                  {/* Import CSV into existing plan */}
                  {status !== 'ratified' && (
                    <Button
                      size="sm"
                      variant="outline"
                      leftSection={<IconUpload size={16} />}
                      onClick={handleImportCSV}
                      loading={importMutation.isPending}
                    >
                      Import CSV
                    </Button>
                  )}

                  {/* Status actions */}
                  {status === 'planning' && (
                    <>
                      <Button
                        size="sm"
                        variant="light"
                        color="yellow"
                        leftSection={<IconCheck size={16} />}
                        onClick={() => setConfirmModal({
                          action: 'approved',
                          title: 'Approve Budget Plan',
                          message: `Mark the ${selectedYear} budget plan as approved? This indicates the board has reviewed and accepted the plan.`,
                        })}
                      >
                        Approve
                      </Button>
                      <Button
                        size="sm"
                        variant="light"
                        color="red"
                        leftSection={<IconTrash size={16} />}
                        onClick={() => setConfirmModal({
                          action: 'delete',
                          title: 'Delete Budget Plan',
                          message: `Permanently delete the ${selectedYear} budget plan? This cannot be undone.`,
                        })}
                      >
                        Delete
                      </Button>
                    </>
                  )}
                  {status === 'approved' && (
                    <>
                      <Button
                        size="sm"
                        variant="light"
                        leftSection={<IconArrowBack size={16} />}
                        onClick={() => setConfirmModal({
                          action: 'planning',
                          title: 'Revert to Planning',
                          message: `Revert the ${selectedYear} budget plan back to planning status?`,
                        })}
                      >
                        Revert to Planning
                      </Button>
                      <Button
                        size="sm"
                        color="green"
                        leftSection={<IconCheck size={16} />}
                        onClick={() => setConfirmModal({
                          action: 'ratified',
                          title: 'Ratify Budget',
                          message: `Ratify the ${selectedYear} budget? This will create the official budget for ${selectedYear} in Financials, overwriting any existing budget data for that year.`,
                        })}
                      >
                        Ratify Budget
                      </Button>
                    </>
                  )}
                  {status === 'ratified' && (
                    <Button
                      size="sm"
                      variant="light"
                      color="orange"
                      leftSection={<IconArrowBack size={16} />}
                      onClick={() => setConfirmModal({
                        action: 'approved',
                        title: 'Revert from Ratified',
                        message: `Revert the ${selectedYear} budget from ratified to approved? This will remove the official budget for ${selectedYear} from Financials.`,
                      })}
                    >
                      Revert to Approved
                    </Button>
                  )}

                  {/* Edit/Save */}
                  {status !== 'ratified' && (
                    <>
                      {!isEditing ? (
                        <Button
                          size="sm"
                          variant="outline"
                          leftSection={<IconPencil size={16} />}
                          onClick={() => setIsEditing(true)}
                        >
                          Edit
                        </Button>
                      ) : (
                        <>
                          <Button
                            size="sm"
                            variant="outline"
                            color="gray"
                            leftSection={<IconX size={16} />}
                            onClick={handleCancelEdit}
                          >
                            Cancel
                          </Button>
                          <Button
                            size="sm"
                            leftSection={<IconDeviceFloppy size={16} />}
                            onClick={() => saveMutation.mutate()}
                            loading={saveMutation.isPending}
                          >
                            Save
                          </Button>
                        </>
                      )}
                    </>
                  )}
                </>
              )}
            </Group>
          </Group>

          {/* Summary cards */}
          <Group>
            <Card withBorder p="sm">
              <Text size="xs" c="dimmed">Operating Income</Text>
              <Text fw={700} c="green">{fmt(totalOperatingIncome)}</Text>
            </Card>
            {totalReserveIncome > 0 && (
              <Card withBorder p="sm">
                <Text size="xs" c="dimmed">Reserve Income</Text>
                <Text fw={700} c="violet">{fmt(totalReserveIncome)}</Text>
              </Card>
            )}
            <Card withBorder p="sm">
              <Text size="xs" c="dimmed">Total Expenses</Text>
              <Text fw={700} c="red">{fmt(totalExpense)}</Text>
            </Card>
            <Card withBorder p="sm">
              <Text size="xs" c="dimmed">Net (Operating)</Text>
              <Text fw={700} c={totalOperatingIncome - totalExpense >= 0 ? 'green' : 'red'}>
                {fmt(totalOperatingIncome - totalExpense)}
              </Text>
            </Card>
          </Group>

          {/* Data table */}
          <div style={{ overflowX: 'auto' }}>
            <Table striped highlightOnHover style={{ minWidth: 1600 }}>
              <Table.Thead>
                <Table.Tr>
                  <Table.Th style={{ position: 'sticky', left: 0, background: stickyBg, zIndex: 2, minWidth: 120 }}>Acct #</Table.Th>
                  <Table.Th style={{ position: 'sticky', left: 120, background: stickyBg, zIndex: 2, minWidth: 220 }}>Account Name</Table.Th>
                  {monthLabels.map((m) => (
                    <Table.Th key={m} ta="right" style={{ minWidth: 90 }}>{m}</Table.Th>
                  ))}
                  <Table.Th ta="right" style={{ minWidth: 110 }}>Annual</Table.Th>
                </Table.Tr>
              </Table.Thead>
              <Table.Tbody>
                {lineData.length === 0 && (
                  <Table.Tr>
                    <Table.Td colSpan={15}>
                      <Text ta="center" c="dimmed" py="lg">No budget plan lines.</Text>
                    </Table.Td>
                  </Table.Tr>
                )}
                {['income', 'expense'].map((type) => {
                  const lines = lineData.filter((b) => b.account_type === type);
                  if (lines.length === 0) return null;

                  const sectionBg = type === 'income' ? incomeSectionBg : expenseSectionBg;
                  const sectionTotal = lines.reduce((sum, l) => sum + (l.annual_total || 0), 0);

                  return [
                    <Table.Tr key={`header-${type}`} style={{ background: sectionBg }}>
                      <Table.Td
                        colSpan={2}
                        fw={700}
                        tt="capitalize"
                        style={{ position: 'sticky', left: 0, background: sectionBg, zIndex: 2 }}
                      >
                        {type}
                      </Table.Td>
                      {monthLabels.map((m) => <Table.Td key={m} />)}
                      <Table.Td ta="right" fw={700} ff="monospace">{fmt(sectionTotal)}</Table.Td>
                    </Table.Tr>,
                    ...lines.map((line) => {
                      const idx = lineData.indexOf(line);
                      return (
                        <Table.Tr key={line.id || `${line.account_id}-${line.fund_type}`}>
                          <Table.Td
                            style={{
                              position: 'sticky', left: 0, background: stickyBg,
                              zIndex: 1, borderRight: `1px solid ${stickyBorder}`,
                            }}
                          >
                            <Text size="sm" c="dimmed" ff="monospace">{line.account_number}</Text>
                          </Table.Td>
                          <Table.Td
                            style={{
                              position: 'sticky', left: 120, background: stickyBg,
                              zIndex: 1, borderRight: `1px solid ${stickyBorder}`,
                            }}
                          >
                            <Group gap={6} wrap="nowrap">
                              <Text size="sm" style={{ whiteSpace: 'nowrap' }}>{line.account_name}</Text>
                              {line.fund_type === 'reserve' && <Badge size="xs" color="violet">R</Badge>}
                              {line.is_manually_adjusted && <Badge size="xs" color="orange" variant="dot">edited</Badge>}
                            </Group>
                          </Table.Td>
                          {monthKeys.map((m) => (
                            <Table.Td key={m} p={2}>
                              {cellsEditable ? (
                                <NumberInput
                                  value={(line as any)[m] || 0}
                                  onChange={(v) => updateCell(idx, m, Number(v) || 0)}
                                  size="xs"
                                  hideControls
                                  decimalScale={2}
                                  min={0}
                                  styles={{ input: { textAlign: 'right', fontFamily: 'monospace' } }}
                                />
                              ) : (
                                <Text size="sm" ta="right" ff="monospace">
                                  {fmt((line as any)[m] || 0)}
                                </Text>
                              )}
                            </Table.Td>
                          ))}
                          <Table.Td ta="right" fw={500} ff="monospace">
                            {fmt(line.annual_total || 0)}
                          </Table.Td>
                        </Table.Tr>
                      );
                    }),
                  ];
                })}
              </Table.Tbody>
            </Table>
          </div>
        </>
      )}

      {/* Confirmation modal */}
      <Modal
        opened={!!confirmModal}
        onClose={() => setConfirmModal(null)}
        title={confirmModal?.title || ''}
        centered
      >
        <Stack>
          <Text size="sm">{confirmModal?.message}</Text>
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setConfirmModal(null)}>Cancel</Button>
            <Button
              color={confirmModal?.action === 'delete' ? 'red' : undefined}
              loading={statusMutation.isPending || deleteMutation.isPending || inflationMutation.isPending}
              onClick={() => {
                if (!confirmModal) return;
                if (confirmModal.action === 'delete') {
                  deleteMutation.mutate();
                } else if (confirmModal.action === 'inflation') {
                  inflationMutation.mutate();
                  setConfirmModal(null);
                } else {
                  statusMutation.mutate(confirmModal.action);
                }
              }}
            >
              Confirm
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Stack>
  );
}
