import { useState, useRef } from "react";
import { useExpensesContext } from "../ExpensesProvider";
import { ExpensesTable } from "./ExpensesTable";
import { PayExpenseDialog } from "./PayExpenseDialog";
import { NewExpenseDialog } from "./NewExpenseDialog";
import {
  ResponsiveDialog,
  ResponsiveDialogContent,
  ResponsiveDialogHeader,
  ResponsiveDialogTitle,
  ResponsiveDialogDescription,
} from "@/components/ui/responsive-dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Plus, Upload, Search, X } from "lucide-react";
import type { Expense, ImportExpensesResult } from "@/lib/api";

const priceFormatter = new Intl.NumberFormat("es-AR", {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});

export function ExpensesTabContent() {
  const {
    expenses,
    isLoadingExpenses,
    statusFilter,
    setStatusFilter,
    page,
    setPage,
    pageSize,
    monthlyTotals,
    isLoadingTotals,
    totalPending,
    isLoadingTotalPending,
    periodicExpenses,
    periodicExpenseFilter,
    setPeriodicExpenseFilter,
    searchInput,
    setSearchInput,
    importExpenses,
  } = useExpensesContext();

  const [payDialogExpense, setPayDialogExpense] = useState<Expense | null>(null);
  const [newExpenseOpen, setNewExpenseOpen] = useState(false);

  const [importDialogOpen, setImportDialogOpen] = useState(false);
  const [importing, setImporting] = useState(false);
  const [importResult, setImportResult] = useState<ImportExpensesResult | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const filters = [
    { value: "PENDING", label: "Pendientes" },
    { value: "PAYED", label: "Pagados" },
    { value: "all", label: "Todos" },
  ] as const;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-2 flex-wrap">
        <div className="flex gap-1">
          {filters.map((f) => (
            <Button
              key={f.value}
              variant={statusFilter === f.value ? "default" : "outline"}
              size="xs"
              onClick={() => { setStatusFilter(f.value); setPage(1); }}
            >
              {f.label}
            </Button>
          ))}
        </div>
        <div className="flex items-center gap-2">
          <div className="relative w-48">
            <Search className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Buscar por descripción..."
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              className="pl-8 pr-8"
            />
            {searchInput && (
              <button
                type="button"
                onClick={() => setSearchInput("")}
                className="absolute right-1.5 top-1/2 -translate-y-1/2 flex size-5 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
              >
                <X className="size-3.5" />
              </button>
            )}
          </div>
          <Select
            value={periodicExpenseFilter !== undefined ? String(periodicExpenseFilter) : "all"}
            onValueChange={(val) => {
              setPeriodicExpenseFilter(val === "all" ? undefined : Number(val));
              setPage(1);
            }}
          >
            <SelectTrigger className="w-52">
              <SelectValue placeholder="Todos los gastos" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Todos los gastos periódicos</SelectItem>
              {periodicExpenses.map((pe) => (
                <SelectItem key={pe.id} value={String(pe.id)}>
                  {pe.description}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button onClick={() => setImportDialogOpen(true)} variant="outline" size="sm">
            <Upload className="size-4" />
            Importar
          </Button>
          <Button onClick={() => setNewExpenseOpen(true)} size="sm">
            <Plus className="size-4" />
            Nuevo gasto
          </Button>
        </div>
      </div>

      {isLoadingExpenses ? (
        <p className="text-sm text-muted-foreground">Cargando...</p>
      ) : (
        <ExpensesTable
          data={expenses.data}
          onPay={setPayDialogExpense}
          page={expenses.page}
          total={expenses.total}
          pageSize={expenses.pageSize}
          onPageChange={setPage}
        />
      )}

      <div className="grid gap-4 sm:grid-cols-3">
        <div className="rounded-lg border p-4">
          <p className="text-sm text-muted-foreground">Total Pagado</p>
          <p className="text-2xl font-bold tabular-nums">
            {isLoadingTotals
              ? "..."
              : `$${priceFormatter.format(monthlyTotals?.payed ?? 0)}`}
          </p>
        </div>
        <div className="rounded-lg border p-4">
          <p className="text-sm text-muted-foreground">Total Pendiente del Mes</p>
          <p className="text-2xl font-bold tabular-nums">
            {isLoadingTotals
              ? "..."
              : `$${priceFormatter.format(monthlyTotals?.pending ?? 0)}`}
          </p>
        </div>
        <div className="rounded-lg border p-4">
          <p className="text-sm text-muted-foreground">Total Pendiente General</p>
          <p className="text-2xl font-bold tabular-nums">
            {isLoadingTotalPending
              ? "..."
              : `$${priceFormatter.format(totalPending?.total ?? 0)}`}
          </p>
        </div>
      </div>

      <PayExpenseDialog
        expense={payDialogExpense}
        open={payDialogExpense !== null}
        onOpenChange={(open) => {
          if (!open) setPayDialogExpense(null);
        }}
      />

      <NewExpenseDialog open={newExpenseOpen} onOpenChange={setNewExpenseOpen} />

      <ResponsiveDialog open={importDialogOpen} onOpenChange={(open) => {
        setImportDialogOpen(open);
        if (!open) {
          setImportResult(null);
        }
      }}>
        <ResponsiveDialogContent>
          <ResponsiveDialogHeader>
            <ResponsiveDialogTitle>Importar gastos</ResponsiveDialogTitle>
            <ResponsiveDialogDescription>
              Seleccioná un archivo CSV (delimitado por pipes) para importar gastos.
            </ResponsiveDialogDescription>
          </ResponsiveDialogHeader>

          {importResult ? (
            <div className="space-y-3 py-4">
              <p className="text-sm font-medium">Importación completada</p>
              <ul className="space-y-1 text-sm">
                <li className="flex items-center gap-2">
                  <span className="size-2 rounded-full bg-green-500" />
                  Importados: {importResult.imported}
                </li>
                <li className="flex items-center gap-2">
                  <span className="size-2 rounded-full bg-yellow-500" />
                  Omitidos (duplicados): {importResult.skipped}
                </li>
              </ul>
              {importResult.errors && importResult.errors.length > 0 && (
                <div className="rounded-md border border-destructive/50 bg-destructive/10 p-3">
                  <p className="mb-1 text-xs font-medium text-destructive">Errores:</p>
                  <ul className="list-inside list-disc text-xs text-destructive/80">
                    {importResult.errors.map((err, i) => (
                      <li key={i}>{err}</li>
                    ))}
                  </ul>
                </div>
              )}
              <Button className="w-full" onClick={() => setImportDialogOpen(false)}>
                Cerrar
              </Button>
            </div>
          ) : (
            <div className="space-y-4 py-4">
              <input
                ref={fileInputRef}
                type="file"
                accept=".csv,.txt"
                className="block w-full text-sm text-muted-foreground file:mr-3 file:rounded-md file:border-0 file:bg-primary file:px-3 file:py-1.5 file:text-xs file:text-primary-foreground hover:file:bg-primary/90"
              />
              <Button
                className="w-full"
                disabled={importing}
                onClick={async () => {
                  const file = fileInputRef.current?.files?.[0];
                  if (!file) return;
                  setImporting(true);
                  try {
                    const result = await importExpenses(file);
                    setImportResult(result);
                  } catch (err) {
                    const message = err instanceof Error ? err.message : String(err);
                    setImportResult({ imported: 0, skipped: 0, errors: [message] });
                  } finally {
                    setImporting(false);
                  }
                }}
              >
                {importing ? "Importando..." : "Importar"}
              </Button>
            </div>
          )}
        </ResponsiveDialogContent>
      </ResponsiveDialog>
    </div>
  );
}
