import { writeFileSync } from "fs";

writeFileSync("app/transactions/page.tsx", `"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { AppShell } from "../../components/app-shell";
import { apiFetch, getStoredToken } from "../../lib/api";

type ApiResponse<T> = {
  data: T;
  meta: { timestamp: string; version: "v1" };
  error: null | { message: string; code?: string };
};

type TransactionRow = {
  id: string;
  name?: string;
  description?: string;
  amount: string;
  category?: string | null;
  note?: string | null;
  status?: string;
  hidden?: boolean;
  date: string;
  accountId?: string | null;
};

type Account = {
  id: string;
  institutionName: string;
  accountType: string;
  mask?: string | null;
};

type ImportResult = {
  imported: number;
  skipped: number;
  errors?: string[];
};

export default function TransactionsPage() {
  const [rows, setRows] = useState<TransactionRow[]>([]);
  const [status, setStatus] = useState("Loading transactions...");
  const [summary, setSummary] = useState<{
    total: string; count: number; income?: string; expense?: string; net?: string;
  } | null>(null);
  const [datePreset, setDatePreset] = useState("this_month");
  const [showFilters, setShowFilters] = useState(false);
  const [accounts, setAccounts] = useState<Account[]>([]);
  const [autoSync, setAutoSync] = useState(true);
  const [isSyncing, setIsSyncing] = useState(false);
  const [showManual, setShowManual] = useState(false);
  const [showImport, setShowImport] = useState(false);
  const [importStatus, setImportStatus] = useState("");
  const [importLoading, setImportLoading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [manualForm, setManualForm] = useState({
    accountId: "",
    date: new Date().toISOString().slice(0, 10),
    description: "",
    amount: "",
    category: "",
    note: "",
  });
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState({ category: "", note: "", hidden: false });
  const [filters, setFilters] = useState({
    startDate: "", endDate: "", minAmount: "", maxAmount: "",
    category: "", source: "", search: "", includeHidden: false,
  });

  const applyPreset = (preset: string) => {
    setDatePreset(preset);
    if (preset === "custom") return;
    const now = new Date();
    const end = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    let start = new Date(end);
    if (preset === "this_month") {
      start = new Date(end.getFullYear(), end.getMonth(), 1);
    } else if (preset === "last_month") {
      start = new Date(end.getFullYear(), end.getMonth() - 1, 1);
      end.setDate(0);
    } else if (preset === "last_6_months") {
      start = new Date(end.getFullYear(), end.getMonth() - 5, 1);
    } else if (preset === "last_year") {
      start = new Date(end.getFullYear() - 1, 0, 1);
      end.setMonth(11, 31);
    }
    const fmt = (d: Date) => d.toISOString().slice(0, 10);
    setFilters((prev) => ({ ...prev, startDate: fmt(start), endDate: fmt(end) }));
  };

  const buildQuery = () => {
    const params = new URLSearchParams();
    if (filters.startDate) params.set("start_date", filters.startDate);
    if (filters.endDate) params.set("end_date", filters.endDate);
    if (filters.minAmount) params.set("min_amount", filters.minAmount);
    if (filters.maxAmount) params.set("max_amount", filters.maxAmount);
    if (filters.category) params.set("category", filters.category);
    if (filters.source) params.set("source", filters.source);
    if (filters.search) params.set("search", filters.search);
    if (filters.includeHidden) params.set("include_hidden", "true");
    return params.toString() ? \`?\${params.toString()}\` : "";
  };

  const load = async () => {
    const query = buildQuery();
    const res = await apiFetch<TransactionRow[]>(\`/api/transactions\${query}\`);
    if (res.error) {
      setStatus(res.error.message ?? "Unable to load transactions.");
      return;
    }
    setRows(res.data ?? []);
    setStatus((res.data ?? []).length ? "" : "No transactions yet.");
  };

  const loadAccounts = async () => {
    const res = await apiFetch<Account[]>("/api/accounts");
    if (!res.error) setAccounts(res.data ?? []);
  };

  const loadSummary = async () => {
    const query = buildQuery();
    const res = await apiFetch<{ total: string; count: number }>(\`/api/transactions/summary\${query}\`);
    if (!res.error) setSummary(res.data);
  };

  useEffect(() => {
    applyPreset("this_month");
    load();
    loadSummary();
    loadAccounts();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!autoSync) return;
    const id = setInterval(() => { onSync(); }, 5 * 60 * 1000);
    return () => clearInterval(id);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [autoSync, filters.startDate, filters.endDate]);

  const onSync = async () => {
    if (isSyncing) return;
    setIsSyncing(true);
    setStatus("Syncing transactions...");
    const res = await apiFetch<unknown>("/api/transactions/sync", {
      method: "POST",
      body: JSON.stringify({ startDate: filters.startDate || undefined, endDate: filters.endDate || undefined }),
    });
    if (res.error) {
      setStatus(res.error.message ?? "Sync failed.");
      setIsSyncing(false);
      return;
    }
    setStatus("Sync complete.");
    await load();
    await loadSummary();
    setIsSyncing(false);
  };

  const onImportCsv = async (file: File) => {
    setImportLoading(true);
    setImportStatus("Uploading...");
    const formData = new FormData();
    formData.append("file", file);
    const token = getStoredToken();
    try {
      const res = await fetch("/api/transactions/import", {
        method: "POST",
        headers: token ? { Authorization: \`Bearer \${token}\` } : {},
        body: formData,
      });
      const payload = (await res.json()) as ApiResponse<ImportResult>;
      if (!res.ok || payload.error) {
        setImportStatus(payload.error?.message ?? "Import failed.");
        setImportLoading(false);
        return;
      }
      const r = payload.data;
      setImportStatus(\`Imported \${r.imported} transaction\${r.imported === 1 ? "" : "s"}, skipped \${r.skipped} duplicate\${r.skipped === 1 ? "" : "s"}.\`);
      await load();
      await loadSummary();
    } catch {
      setImportStatus("Import failed. Please try again.");
    }
    setImportLoading(false);
  };

  const formatAmount = (value: string) => {
    const numeric = Number.parseFloat(value.replace(/[^0-9.-]/g, ""));
    if (Number.isNaN(numeric)) return { display: value, tone: "text-foreground" };
    return {
      display: numeric < 0 ? \`-\$\${Math.abs(numeric).toFixed(2)}\` : \`\$\${numeric.toFixed(2)}\`,
      tone: numeric < 0 ? "text-foreground" : "text-primary font-bold",
    };
  };

  const onManualCreate = async (event: React.FormEvent) => {
    event.preventDefault();
    const amount = Number.parseFloat(manualForm.amount);
    if (Number.isNaN(amount)) { setStatus("Invalid amount."); return; }
    setStatus("Saving manual transaction...");
    const res = await apiFetch<unknown>("/api/transactions/manual", {
      method: "POST",
      body: JSON.stringify({
        accountId: manualForm.accountId || undefined,
        date: manualForm.date,
        description: manualForm.description,
        amount,
        category: manualForm.category || undefined,
        note: manualForm.note || undefined,
      }),
    });
    if (res.error) { setStatus(res.error.message ?? "Unable to save transaction."); return; }
    setManualForm((prev) => ({ ...prev, description: "", amount: "", category: "", note: "" }));
    setShowManual(false);
    setStatus("Manual transaction saved.");
    await load();
    await loadSummary();
  };

  const startEdit = (row: TransactionRow) => {
    setEditingId(row.id);
    setEditForm({ category: row.category ?? "", note: row.note ?? "", hidden: Boolean(row.hidden) });
  };

  const saveEdit = async () => {
    if (!editingId) return;
    setStatus("Saving edits...");
    const res = await apiFetch<unknown>(\`/api/transactions/\${editingId}/derived\`, {
      method: "PATCH",
      body: JSON.stringify({
        userCategory: editForm.category || undefined,
        userNotes: editForm.note || undefined,
        isHidden: editForm.hidden,
      }),
    });
    if (res.error) { setStatus(res.error.message ?? "Unable to save edits."); return; }
    setEditingId(null);
    setStatus("Transaction updated.");
    await load();
    await loadSummary();
  };

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

  return (
    <AppShell title="Transactions" subtitle="View, sync, and categorize your transactions.">
      {/* Action bar */}
      <div className="flex flex-wrap items-center gap-2 text-sm mb-6">
        <span className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-secondary/50 border border-border text-muted-foreground">
          <span className="h-2 w-2 rounded-full bg-primary" />
          {datePreset === "custom" ? "Custom range" : datePreset.replace(/_/g, " ")}
        </span>

        <button onClick={onSync} className="ml-auto px-3 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-bold hover:bg-primary/90 transition-colors">
          {isSyncing ? "Syncing..." : "Sync"}
        </button>
        <button onClick={() => setAutoSync((prev) => !prev)} className={\`px-3 py-2 rounded-lg border text-sm font-medium transition-colors \${autoSync ? "bg-primary/10 border-primary/30 text-primary" : "bg-background border-border text-foreground hover:bg-secondary"}\`}>
          Auto {autoSync ? "On" : "Off"}
        </button>
        <button onClick={() => setShowManual((prev) => !prev)} className="px-3 py-2 rounded-lg bg-background border border-border text-foreground text-sm font-medium hover:bg-secondary transition-colors">
          {showManual ? "Hide manual" : "Add manual"}
        </button>
        <button onClick={() => { setShowImport((prev) => !prev); setImportStatus(""); }} className="px-3 py-2 rounded-lg bg-background border border-border text-foreground text-sm font-medium hover:bg-secondary transition-colors">
          {showImport ? "Hide import" : "Import CSV"}
        </button>
        <Link href={\`/exports\${buildQuery()}\`} className="px-3 py-2 rounded-lg bg-background border border-border text-foreground text-sm font-medium hover:bg-secondary transition-colors">
          Export
        </Link>
        <button onClick={() => setShowFilters((prev) => !prev)} className="px-3 py-2 rounded-lg bg-background border border-border text-foreground text-sm font-medium hover:bg-secondary transition-colors">
          {showFilters ? "Hide filters" : "Filters"}
        </button>
      </div>

      {/* CSV Import panel */}
      {showImport && (
        <div className="mb-6 glass-panel rounded-xl p-5 shadow-sm">
          <p className="text-sm font-bold text-foreground mb-1">Import CSV</p>
          <p className="text-xs text-muted-foreground mb-4">
            Supports Chase, Bank of America, Wells Fargo, and generic CSV formats. Duplicate transactions are skipped automatically.
          </p>
          <div
            className="border-2 border-dashed border-border rounded-xl p-8 text-center cursor-pointer hover:border-primary/50 transition-colors"
            onClick={() => fileInputRef.current?.click()}
            onDragOver={(e) => e.preventDefault()}
            onDrop={(e) => {
              e.preventDefault();
              const file = e.dataTransfer.files[0];
              if (file && file.name.endsWith(".csv")) onImportCsv(file);
            }}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept=".csv"
              className="hidden"
              onChange={(e) => { const f = e.target.files?.[0]; if (f) onImportCsv(f); }}
            />
            <svg className="mx-auto h-8 w-8 text-muted-foreground mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
            </svg>
            {importLoading ? (
              <p className="text-sm text-muted-foreground">Uploading...</p>
            ) : (
              <p className="text-sm text-muted-foreground">Drop a CSV file here or <span className="text-primary font-medium">click to browse</span></p>
            )}
          </div>
          {importStatus && (
            <p className="mt-3 text-sm text-muted-foreground">{importStatus}</p>
          )}
        </div>
      )}

      {/* Manual transaction form */}
      {showManual && (
        <div className="mb-6 glass-panel rounded-xl p-5 shadow-sm">
          <p className="text-sm font-bold text-foreground mb-4">Add Manual Transaction</p>
          <form onSubmit={onManualCreate} className="grid gap-3 md:grid-cols-3">
            <div>
              <label className={labelCls}>Date</label>
              <input type="date" value={manualForm.date} onChange={(e) => setManualForm((p) => ({ ...p, date: e.target.value }))} className={inputCls} required />
            </div>
            <div>
              <label className={labelCls}>Description</label>
              <input type="text" value={manualForm.description} onChange={(e) => setManualForm((p) => ({ ...p, description: e.target.value }))} className={inputCls} required />
            </div>
            <div>
              <label className={labelCls}>Amount (negative = expense)</label>
              <input type="number" step="0.01" value={manualForm.amount} onChange={(e) => setManualForm((p) => ({ ...p, amount: e.target.value }))} className={inputCls} required placeholder="-42.50" />
            </div>
            <div>
              <label className={labelCls}>Category</label>
              <input type="text" value={manualForm.category} onChange={(e) => setManualForm((p) => ({ ...p, category: e.target.value }))} className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>Account</label>
              <select value={manualForm.accountId} onChange={(e) => setManualForm((p) => ({ ...p, accountId: e.target.value }))} className={inputCls}>
                <option value="">— No account —</option>
                {accounts.map((a) => (
                  <option key={a.id} value={a.id}>{a.institutionName} {a.mask ? \`••\${a.mask}\` : ""}</option>
                ))}
              </select>
            </div>
            <div>
              <label className={labelCls}>Note</label>
              <input type="text" value={manualForm.note} onChange={(e) => setManualForm((p) => ({ ...p, note: e.target.value }))} className={inputCls} />
            </div>
            <div className="md:col-span-3 flex justify-end gap-2">
              <button type="button" onClick={() => setShowManual(false)} className="px-4 py-2 rounded-lg border border-border text-sm text-foreground hover:bg-secondary">Cancel</button>
              <button type="submit" className="px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-bold hover:bg-primary/90">Save</button>
            </div>
          </form>
        </div>
      )}

      {/* Filters */}
      {showFilters && (
        <div className="mb-6 glass-panel rounded-xl p-5 shadow-sm">
          <div className="grid gap-4 md:grid-cols-3">
            <div>
              <label className={labelCls}>Date range</label>
              <select value={datePreset} onChange={(e) => applyPreset(e.target.value)} className={inputCls}>
                <option value="this_month">This month</option>
                <option value="last_month">Last month</option>
                <option value="last_6_months">Last 6 months</option>
                <option value="last_year">Last year</option>
                <option value="custom">Custom</option>
              </select>
            </div>
            <div>
              <label className={labelCls}>Start date</label>
              <input type="date" value={filters.startDate} onChange={(e) => setFilters((p) => ({ ...p, startDate: e.target.value }))} className={inputCls} disabled={datePreset !== "custom"} />
            </div>
            <div>
              <label className={labelCls}>End date</label>
              <input type="date" value={filters.endDate} onChange={(e) => setFilters((p) => ({ ...p, endDate: e.target.value }))} className={inputCls} disabled={datePreset !== "custom"} />
            </div>
            <div>
              <label className={labelCls}>Search</label>
              <input type="text" value={filters.search} onChange={(e) => setFilters((p) => ({ ...p, search: e.target.value }))} className={inputCls} placeholder="Description..." />
            </div>
            <div>
              <label className={labelCls}>Category</label>
              <input type="text" value={filters.category} onChange={(e) => setFilters((p) => ({ ...p, category: e.target.value }))} className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>Min amount</label>
              <input type="number" step="0.01" value={filters.minAmount} onChange={(e) => setFilters((p) => ({ ...p, minAmount: e.target.value }))} className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>Max amount</label>
              <input type="number" step="0.01" value={filters.maxAmount} onChange={(e) => setFilters((p) => ({ ...p, maxAmount: e.target.value }))} className={inputCls} />
            </div>
            <div className="flex items-end gap-2">
              <label className="flex items-center gap-2 text-sm text-foreground cursor-pointer">
                <input type="checkbox" checked={filters.includeHidden} onChange={(e) => setFilters((p) => ({ ...p, includeHidden: e.target.checked }))} className="rounded border-border text-primary focus:ring-primary" />
                Include hidden
              </label>
            </div>
            <div className="flex items-end">
              <button onClick={() => { load(); loadSummary(); }} className="w-full px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-bold hover:bg-primary/90">Apply</button>
            </div>
          </div>
        </div>
      )}

      {/* Summary cards */}
      {summary && (
        <div className="mb-6 grid gap-3 md:grid-cols-3">
          {[
            { label: "Total", value: \`\$\${Math.abs(Number.parseFloat(summary.total ?? "0")).toFixed(2)}\`, sub: \`\${summary.count} transactions\` },
            { label: "Income", value: \`+\$\${Math.abs(Number.parseFloat(summary.income ?? "0")).toFixed(2)}\`, sub: "Credits" },
            { label: "Expenses", value: \`-\$\${Math.abs(Number.parseFloat(summary.expense ?? "0")).toFixed(2)}\`, sub: "Debits" },
          ].map((c) => (
            <div key={c.label} className="glass-panel rounded-xl p-4 shadow-sm">
              <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground font-semibold">{c.label}</p>
              <p className="mt-2 text-xl font-bold text-foreground">{c.value}</p>
              <p className="text-xs text-muted-foreground">{c.sub}</p>
            </div>
          ))}
        </div>
      )}

      {/* Transaction table */}
      <div className="glass-panel rounded-2xl shadow-sm overflow-hidden">
        {status && (
          <div className="px-6 py-3 bg-secondary/30 border-b border-border text-sm text-muted-foreground">{status}</div>
        )}
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs text-muted-foreground">
            <thead className="text-[0.65rem] uppercase tracking-[0.18em] font-semibold bg-secondary/20">
              <tr>
                <th className="px-4 py-3">Date</th>
                <th className="px-4 py-3">Description</th>
                <th className="px-4 py-3">Category</th>
                <th className="px-4 py-3 text-right">Amount</th>
                <th className="px-4 py-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row) =>
                editingId === row.id ? (
                  <tr key={row.id} className="border-b border-border bg-secondary/10">
                    <td className="px-4 py-3" colSpan={2}>
                      <div className="flex gap-2">
                        <input
                          type="text"
                          value={editForm.category}
                          onChange={(e) => setEditForm((p) => ({ ...p, category: e.target.value }))}
                          placeholder="Category"
                          className="w-28 rounded border border-border bg-background px-2 py-1 text-xs text-foreground focus:border-primary focus:outline-none"
                        />
                        <input
                          type="text"
                          value={editForm.note}
                          onChange={(e) => setEditForm((p) => ({ ...p, note: e.target.value }))}
                          placeholder="Note"
                          className="flex-1 rounded border border-border bg-background px-2 py-1 text-xs text-foreground focus:border-primary focus:outline-none"
                        />
                        <label className="flex items-center gap-1 text-xs text-foreground">
                          <input type="checkbox" checked={editForm.hidden} onChange={(e) => setEditForm((p) => ({ ...p, hidden: e.target.checked }))} />
                          Hide
                        </label>
                      </div>
                    </td>
                    <td className="px-4 py-3" colSpan={3}>
                      <div className="flex gap-2 justify-end">
                        <button onClick={saveEdit} className="rounded bg-primary px-3 py-1 text-[11px] font-bold text-primary-foreground hover:bg-primary/90">Save</button>
                        <button onClick={() => setEditingId(null)} className="rounded border border-border px-3 py-1 text-[11px] text-foreground hover:bg-secondary">Cancel</button>
                      </div>
                    </td>
                  </tr>
                ) : (
                  <tr key={row.id} className={\`border-b border-border hover:bg-secondary/20 transition-colors \${row.hidden ? "opacity-50" : ""}\`}>
                    <td className="px-4 py-3 font-medium whitespace-nowrap">
                      {new Date(row.date).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" })}
                    </td>
                    <td className="px-4 py-3 text-foreground font-medium max-w-[200px] truncate">
                      {row.description ?? row.name ?? "—"}
                    </td>
                    <td className="px-4 py-3">
                      {row.category ? (
                        <span className="inline-flex rounded-full bg-secondary px-2 py-0.5 text-xs font-medium text-foreground">{row.category}</span>
                      ) : (
                        <span className="text-muted-foreground">—</span>
                      )}
                    </td>
                    <td className={\`px-4 py-3 text-right font-bold \${formatAmount(row.amount).tone}\`}>
                      {formatAmount(row.amount).display}
                    </td>
                    <td className="px-4 py-3 text-right">
                      <button onClick={() => startEdit(row)} className="text-xs text-primary hover:underline">Edit</button>
                    </td>
                  </tr>
                )
              )}
              {!rows.length && !status && (
                <tr>
                  <td colSpan={5} className="px-4 py-12 text-center text-sm text-muted-foreground">
                    No transactions found. Try adjusting your filters or sync your accounts.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </AppShell>
  );
}
`);

console.log("✅ transactions/page.tsx written with CSV import UI and apiFetch");
