"use client";

import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { parseToastSalesCsv, rollupByEntity, toastNameToSlug } from "@/lib/sag/toast-csv";
import type { ToastSalesRow } from "@/lib/sag/types";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { formatCurrency } from "@/lib/utils";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";

interface SavedImport {
  id: string;
  name: string;
  uploadedAt: string;
  rowCount: number;
  rows: ToastSalesRow[];
}

export function ToastCsvUploader() {
  const [parsed, setParsed] = useState<ToastSalesRow[] | null>(null);
  const [filename, setFilename] = useState<string>("");
  const [error, setError] = useState<string>("");
  const [saved, setSaved] = useLocalStorage<SavedImport[]>("sag.toast.imports", []);

  async function onFile(file: File) {
    setError("");
    setFilename(file.name);
    try {
      const text = await file.text();
      const rows = parseToastSalesCsv(text);
      if (rows.length === 0) {
        setError("No rows parsed — is this a Toast Sales Category export?");
        setParsed(null);
        return;
      }
      setParsed(rows);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Parse failed");
    }
  }

  function persist() {
    if (!parsed || !filename) return;
    const entry: SavedImport = {
      id: `${Date.now()}`,
      name: filename,
      uploadedAt: new Date().toISOString(),
      rowCount: parsed.length,
      rows: parsed,
    };
    setSaved([entry, ...saved]);
    setParsed(null);
    setFilename("");
  }

  function deleteSaved(id: string) {
    setSaved(saved.filter((s) => s.id !== id));
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardContent className="p-6">
          <h3 className="text-base font-semibold">Upload Toast CSV</h3>
          <p className="mt-1 text-sm text-muted-foreground">
            Drop a Toast “Sales Category” export. Parsed and saved locally on this device until Supabase is live.
          </p>
          <label
            htmlFor="toast-csv-input"
            className="mt-4 flex flex-col items-center justify-center rounded-md border-2 border-dashed border-muted-foreground/30 bg-muted/20 p-8 cursor-pointer hover:bg-muted/30 transition-colors"
            onDragOver={(e) => e.preventDefault()}
            onDrop={(e) => {
              e.preventDefault();
              const file = e.dataTransfer.files?.[0];
              if (file) onFile(file);
            }}
          >
            <span className="text-3xl">📊</span>
            <span className="mt-2 text-sm font-medium">Drop CSV here or click to choose</span>
            <span className="mt-1 text-xs text-muted-foreground">
              e.g. sales-breakdown-2025.csv or HoursEarningsByRange…
            </span>
            <input
              id="toast-csv-input"
              type="file"
              accept=".csv,text/csv"
              className="sr-only"
              onChange={(e) => {
                const file = e.target.files?.[0];
                if (file) onFile(file);
              }}
            />
          </label>
          {error && (
            <div className="mt-3 rounded-md border border-destructive/20 bg-destructive/5 p-3 text-sm text-destructive">
              {error}
            </div>
          )}
        </CardContent>
      </Card>

      {parsed && (
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3 className="text-base font-semibold">Preview · {filename}</h3>
                <p className="text-xs text-muted-foreground">
                  {parsed.length} rows parsed · {rollupByEntity(parsed).length} entities
                </p>
              </div>
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={() => setParsed(null)}>Cancel</Button>
                <Button variant="brand" size="sm" onClick={persist}>Save import</Button>
              </div>
            </div>
            <ParsedTable rows={rollupByEntity(parsed)} />
          </CardContent>
        </Card>
      )}

      {saved.length > 0 && (
        <Card>
          <CardContent className="p-6">
            <h3 className="text-base font-semibold">Saved imports ({saved.length})</h3>
            <p className="mt-1 text-xs text-muted-foreground">Stored locally in your browser. Will move to Supabase once provisioned.</p>
            <ul className="mt-4 space-y-2">
              {saved.map((entry) => {
                const total = entry.rows
                  .filter((r) => r.diningOption === "")
                  .reduce((a, r) => a + r.netSales, 0);
                return (
                  <li
                    key={entry.id}
                    className="flex items-center justify-between gap-3 rounded-md border bg-background p-3"
                  >
                    <div>
                      <div className="text-sm font-medium">{entry.name}</div>
                      <div className="text-xs text-muted-foreground">
                        {new Date(entry.uploadedAt).toLocaleString()} · {entry.rowCount} rows
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className="text-sm font-mono">{formatCurrency(total)}</span>
                      <Button variant="ghost" size="sm" onClick={() => deleteSaved(entry.id)}>
                        Delete
                      </Button>
                    </div>
                  </li>
                );
              })}
            </ul>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function ParsedTable({ rows }: { rows: ToastSalesRow[] }) {
  const totals = rows.reduce(
    (a, r) => ({
      net: a.net + r.netSales,
      gross: a.gross + r.grossSales,
      items: a.items + r.itemQty,
      tax: a.tax + r.taxAmount,
    }),
    { net: 0, gross: 0, items: 0, tax: 0 }
  );

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead className="border-b bg-muted/40">
          <tr>
            <th className="text-left p-3 font-medium">Sales category (Toast)</th>
            <th className="text-left p-3 font-medium">Mapped to entity</th>
            <th className="text-right p-3 font-medium">Items</th>
            <th className="text-right p-3 font-medium">Net</th>
            <th className="text-right p-3 font-medium">Gross</th>
            <th className="text-right p-3 font-medium">Tax</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => {
            const slug = toastNameToSlug(r.salesCategory);
            const org = slug ? ALL_ORGANIZATIONS.find((o) => o.slug === slug) : undefined;
            return (
              <tr key={i} className="border-b last:border-b-0 hover:bg-muted/20">
                <td className="p-3">{r.salesCategory}</td>
                <td className="p-3">
                  {org ? (
                    <span className="inline-flex items-center gap-2 text-foreground">
                      <span>{org.emoji}</span>
                      <span>{org.name}</span>
                    </span>
                  ) : (
                    <Badge variant="warning" className="text-[10px]">Unmapped</Badge>
                  )}
                </td>
                <td className="p-3 text-right tabular-nums">{r.itemQty.toLocaleString()}</td>
                <td className="p-3 text-right tabular-nums font-medium">{formatCurrency(r.netSales)}</td>
                <td className="p-3 text-right tabular-nums">{formatCurrency(r.grossSales)}</td>
                <td className="p-3 text-right tabular-nums">{formatCurrency(r.taxAmount)}</td>
              </tr>
            );
          })}
        </tbody>
        <tfoot className="border-t bg-muted/30 font-semibold">
          <tr>
            <td colSpan={2} className="p-3">Total</td>
            <td className="p-3 text-right tabular-nums">{totals.items.toLocaleString()}</td>
            <td className="p-3 text-right tabular-nums">{formatCurrency(totals.net)}</td>
            <td className="p-3 text-right tabular-nums">{formatCurrency(totals.gross)}</td>
            <td className="p-3 text-right tabular-nums">{formatCurrency(totals.tax)}</td>
          </tr>
        </tfoot>
      </table>
    </div>
  );
}
