"use client";

import { useEffect, useState } from "react";
import { DataTable } from "@/components/data-table";
import {
  getTransactionReport,
  getReportSummary,
  exportReportPdf,
  getWarehouses,
  ReportRow,
  WarehouseSummary,
  WarehouseRecord,
} from "@/lib/api";

type TransactionTableRow = {
  id: string;
  date: string;
  type: string;
  warehouse: string;
  itemName: string;
  batchNumber: string;
  quantityMt: string;
};

type SummaryTableRow = {
  warehouse: string;
  totalInbound: string;
  totalOutbound: string;
  net: string;
};

const TYPE_OPTIONS = [
  { value: "all", label: "All (In & Out)" },
  { value: "inbound", label: "Stock In only" },
  { value: "outbound", label: "Movement Out only" },
];

// Quick date range presets
function getDateRange(preset: string): { fromDate: string; toDate: string } {
  const today = new Date();
  const toDate = today.toISOString().slice(0, 10);
  const from = new Date(today);

  switch (preset) {
    case "7d": from.setDate(from.getDate() - 7); break;
    case "30d": from.setDate(from.getDate() - 30); break;
    case "3m": from.setMonth(from.getMonth() - 3); break;
    case "6m": from.setMonth(from.getMonth() - 6); break;
    case "1y": from.setFullYear(from.getFullYear() - 1); break;
    default: return { fromDate: "", toDate: "" };
  }
  return { fromDate: from.toISOString().slice(0, 10), toDate };
}

export default function ReportsPage() {
  const [warehouses, setWarehouses] = useState<WarehouseRecord[]>([]);
  const [selectedWarehouses, setSelectedWarehouses] = useState<string[]>([]);
  const [typeFilter, setTypeFilter] = useState<"all" | "inbound" | "outbound">("all");
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [datePreset, setDatePreset] = useState("all");

  const [transactions, setTransactions] = useState<ReportRow[]>([]);
  const [summary, setSummary] = useState<WarehouseSummary[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [exporting, setExporting] = useState(false);
  const [exportError, setExportError] = useState<string | null>(null);

  // Load warehouses for filter
  useEffect(() => {
    getWarehouses().then(setWarehouses).catch(() => {});
  }, []);

  function applyPreset(preset: string) {
    setDatePreset(preset);
    if (preset === "all") {
      setFromDate("");
      setToDate("");
    } else {
      const { fromDate: f, toDate: t } = getDateRange(preset);
      setFromDate(f);
      setToDate(t);
    }
  }

  function toggleWarehouse(name: string) {
    setSelectedWarehouses((prev) =>
      prev.includes(name) ? prev.filter((w) => w !== name) : [...prev, name]
    );
  }

  async function loadReport() {
    setLoading(true);
    setError(null);
    try {
      const params = {
        warehouses: selectedWarehouses.length ? selectedWarehouses : undefined,
        type: typeFilter,
        fromDate: fromDate || undefined,
        toDate: toDate || undefined,
      };
      const [txns, summ] = await Promise.all([
        getTransactionReport(params),
        getReportSummary(params),
      ]);
      setTransactions(txns);
      setSummary(summ);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to load report");
    } finally {
      setLoading(false);
    }
  }

  // Load on mount and when filters change
  useEffect(() => { loadReport(); }, [selectedWarehouses, typeFilter, fromDate, toDate]); // eslint-disable-line react-hooks/exhaustive-deps

  async function handleExportPdf() {
    setExporting(true);
    setExportError(null);
    try {
      const { blob, fileName } = await exportReportPdf({
        warehouses: selectedWarehouses.length ? selectedWarehouses : undefined,
        type: typeFilter,
        fromDate: fromDate || undefined,
        toDate: toDate || undefined,
        title: "Stock Movement Report",
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch (err: unknown) {
      setExportError(err instanceof Error ? err.message : "Export failed");
    } finally {
      setExporting(false);
    }
  }

  const txRows: TransactionTableRow[] = transactions.map((t) => ({
    id: t.id,
    date: t.date,
    type: t.type,
    warehouse: t.warehouse ?? "—",
    itemName: t.itemName ?? "—",
    batchNumber: t.batchNumber ?? "—",
    quantityMt: t.quantityMt.toFixed(2),
  }));

  const summaryRows: SummaryTableRow[] = summary.map((s) => ({
    warehouse: s.warehouse,
    totalInbound: s.totalInbound.toFixed(2),
    totalOutbound: s.totalOutbound.toFixed(2),
    net: s.net.toFixed(2),
  }));

  const totalIn = summary.reduce((s, r) => s + r.totalInbound, 0);
  const totalOut = summary.reduce((s, r) => s + r.totalOutbound, 0);
  const totalNet = totalIn - totalOut;

  return (
    <>
      <section className="hero">
        <h2>Stock Movement Reports</h2>
        <p>Track all inbound and outbound movements by warehouse, date, and type.</p>
      </section>

      <section className="section">
        {/* ── Filter bar ──────────────────────────────────────────────── */}
        <div className="card stack" style={{ marginBottom: 18 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12 }}>
            <h3 style={{ margin: 0, fontSize: "0.96rem" }}>Filters</h3>
            <div style={{ display: "flex", gap: 8 }}>
              <button
                className="button secondary"
                style={{ fontSize: "0.78rem", padding: "8px 14px" }}
                onClick={() => { setSelectedWarehouses([]); setTypeFilter("all"); applyPreset("all"); }}
              >
                Clear All
              </button>
              <button
                className="button"
                style={{ fontSize: "0.78rem", padding: "8px 16px" }}
                onClick={handleExportPdf}
                disabled={exporting}
              >
                {exporting ? "Exporting…" : "Export PDF"}
              </button>
            </div>
          </div>

          {exportError && (
            <div className="snackbar snackbar-error">
              <span>⚠ {exportError}</span>
              <button onClick={() => setExportError(null)} className="snackbar-close">✕</button>
            </div>
          )}

          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 16 }}>
            {/* Type filter */}
            <div className="form-field">
              <label className="form-label">Transaction Type</label>
              <div className="select-wrapper">
                <select
                  className="premium-select"
                  value={typeFilter}
                  onChange={(e) => setTypeFilter(e.target.value as typeof typeFilter)}
                >
                  {TYPE_OPTIONS.map((o) => (
                    <option key={o.value} value={o.value}>{o.label}</option>
                  ))}
                </select>
                <span className="select-chevron">▾</span>
              </div>
            </div>

            {/* Date preset */}
            <div className="form-field">
              <label className="form-label">Date Range</label>
              <div className="select-wrapper">
                <select
                  className="premium-select"
                  value={datePreset}
                  onChange={(e) => applyPreset(e.target.value)}
                >
                  <option value="all">All time</option>
                  <option value="7d">Last 7 days</option>
                  <option value="30d">Last 30 days</option>
                  <option value="3m">Last 3 months</option>
                  <option value="6m">Last 6 months</option>
                  <option value="1y">Last 1 year</option>
                  <option value="custom">Custom range</option>
                </select>
                <span className="select-chevron">▾</span>
              </div>
            </div>

            {/* Custom date range */}
            {datePreset === "custom" && (
              <>
                <div className="form-field">
                  <label className="form-label">From Date</label>
                  <input
                    type="date"
                    className="form-input"
                    value={fromDate}
                    onChange={(e) => setFromDate(e.target.value)}
                  />
                </div>
                <div className="form-field">
                  <label className="form-label">To Date</label>
                  <input
                    type="date"
                    className="form-input"
                    value={toDate}
                    onChange={(e) => setToDate(e.target.value)}
                  />
                </div>
              </>
            )}
          </div>

          {/* Warehouse multi-select */}
          {warehouses.length > 0 && (
            <div className="form-field">
              <label className="form-label">
                Warehouses
                <span className="form-optional">
                  {selectedWarehouses.length === 0 ? "all" : `${selectedWarehouses.length} selected`}
                </span>
              </label>
              <div className="checkbox-group" style={{ display: "flex", flexWrap: "wrap", gap: 4, padding: 10 }}>
                {warehouses.map((w) => (
                  <label key={w._id} className="checkbox-option" style={{ minWidth: 160 }}>
                    <input
                      type="checkbox"
                      checked={selectedWarehouses.includes(w.name)}
                      onChange={() => toggleWarehouse(w.name)}
                      style={{ width: 14, height: 14 }}
                    />
                    {w.name}
                  </label>
                ))}
              </div>
            </div>
          )}
        </div>

        {loading && <p>Loading report…</p>}
        {error && <p className="error">{error}</p>}

        {!loading && !error && (
          <>
            {/* ── Summary cards ──────────────────────────────────────── */}
            <div className="grid grid-4" style={{ marginBottom: 18 }}>
              <div className="card metric">
                <span className="badge ok">Total In</span>
                <strong className="value">{totalIn.toFixed(1)} MT</strong>
                <span className="metric-foot">{transactions.filter((t) => t.type === "inbound").length} transactions</span>
              </div>
              <div className="card metric">
                <span className="badge warn">Total Out</span>
                <strong className="value">{totalOut.toFixed(1)} MT</strong>
                <span className="metric-foot">{transactions.filter((t) => t.type === "outbound").length} transactions</span>
              </div>
              <div className="card metric">
                <span className={`badge ${totalNet >= 0 ? "ok" : "danger"}`}>Net</span>
                <strong className="value" style={{ color: totalNet >= 0 ? "var(--brand)" : "var(--danger)" }}>
                  {totalNet >= 0 ? "+" : ""}{totalNet.toFixed(1)} MT
                </strong>
                <span className="metric-foot">Inbound minus outbound</span>
              </div>
              <div className="card metric">
                <span className="badge ok">Transactions</span>
                <strong className="value">{transactions.length}</strong>
                <span className="metric-foot">Total records</span>
              </div>
            </div>

            {/* ── Summary by warehouse ───────────────────────────────── */}
            {summaryRows.length > 0 && (
              <div style={{ marginBottom: 18 }}>
                <div className="section-header">
                  <div>
                    <h3>Summary by Warehouse</h3>
                    <p>Aggregated totals per warehouse</p>
                  </div>
                </div>
                <DataTable<SummaryTableRow>
                  rows={summaryRows}
                  columns={[
                    { key: "warehouse", label: "Warehouse" },
                    {
                      key: "totalInbound",
                      label: "Total In (MT)",
                      render: (v) => <span style={{ color: "var(--brand)" }}>↑ {String(v)}</span>,
                    },
                    {
                      key: "totalOutbound",
                      label: "Total Out (MT)",
                      render: (v) => <span style={{ color: "var(--warn)" }}>↓ {String(v)}</span>,
                    },
                    {
                      key: "net",
                      label: "Net (MT)",
                      render: (v) => {
                        const n = parseFloat(String(v));
                        return (
                          <strong style={{ color: n >= 0 ? "var(--brand)" : "var(--danger)" }}>
                            {n >= 0 ? "+" : ""}{String(v)}
                          </strong>
                        );
                      },
                    },
                  ]}
                />
              </div>
            )}

            {/* ── Transaction detail ─────────────────────────────────── */}
            <div className="section-header">
              <div>
                <h3>Transaction Detail</h3>
                <p>{txRows.length} record{txRows.length !== 1 ? "s" : ""}</p>
              </div>
            </div>

            {txRows.length === 0 ? (
              <div className="empty-preview">
                <p>No transactions found for the selected filters.</p>
              </div>
            ) : (
              <DataTable<TransactionTableRow>
                rows={txRows}
                columns={[
                  { key: "date", label: "Date" },
                  {
                    key: "type",
                    label: "Type",
                    render: (v) =>
                      v === "inbound"
                        ? <span className="badge ok">↑ Stock In</span>
                        : <span className="badge warn">↓ Movement Out</span>,
                  },
                  { key: "warehouse", label: "Warehouse" },
                  { key: "itemName", label: "Item" },
                  { key: "batchNumber", label: "Batch" },
                  {
                    key: "quantityMt",
                    label: "Quantity (MT)",
                    render: (v, row) => (
                      <strong style={{ color: row.type === "inbound" ? "var(--brand)" : "var(--warn)" }}>
                        {row.type === "inbound" ? "+" : "-"}{String(v)}
                      </strong>
                    ),
                  },
                ]}
              />
            )}
          </>
        )}
      </section>
    </>
  );
}
