import { useCallback, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Building2, ChevronLeft, ChevronRight, Landmark, Loader2, Search } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
  fechamentoBancoPontosService,
  type BancoPontosEstaAtivoFiltro,
  type BancoPontosSaldoItem,
} from "@/services/fechamento/bancoPontos";
import { resolveParceiroFotoUrl } from "@/services/fechamento/parceiroFotoUrl";

const PER_PAGE = 20;

function formatPontos(valor: number): string {
  return valor.toLocaleString("pt-BR", { minimumFractionDigits: 0, maximumFractionDigits: 4 });
}

function iniciais(nome: string): string {
  const p = nome.trim().split(/\s+/).slice(0, 2);
  return p.map((w) => w[0]?.toUpperCase() ?? "").join("") || "?";
}

function getDisplayNome(row: BancoPontosSaldoItem): string {
  if (row.codinome?.trim()) {
    return `${row.nome} (${row.codinome.trim()})`;
  }
  return row.nome;
}

function ParceiroFotoCell({
  nome,
  logoUrl,
  fotoUrl,
}: {
  nome: string;
  logoUrl: string | null;
  fotoUrl?: string | null;
}) {
  const [imgErro, setImgErro] = useState(false);
  const src = resolveParceiroFotoUrl(fotoUrl ?? logoUrl);

  useEffect(() => {
    setImgErro(false);
  }, [src]);
  const classes =
    "h-12 w-12 rounded-lg border border-border object-cover";

  if (!src || imgErro) {
    return (
      <div className="flex h-12 w-12 items-center justify-center rounded-lg border border-border bg-muted text-xs font-semibold text-muted-foreground">
        {iniciais(nome)}
      </div>
    );
  }

  return (
    <img
      src={src}
      alt=""
      className={classes}
      referrerPolicy="no-referrer"
      loading="lazy"
      onError={() => setImgErro(true)}
    />
  );
}

export default function BancoPontos() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [rows, setRows] = useState<BancoPontosSaldoItem[]>([]);
  const [meta, setMeta] = useState({ total: 0, paginaAtual: 1, totalPaginas: 1 });
  const [buscaInput, setBuscaInput] = useState("");
  const [buscaDebounced, setBuscaDebounced] = useState("");
  const [estaAtivo, setEstaAtivo] = useState<BancoPontosEstaAtivoFiltro>("all");
  const [page, setPage] = useState(1);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fechamentoBancoPontosService.listarSaldos({
        estaAtivo,
        busca: buscaDebounced.trim() || undefined,
        page,
        perPage: PER_PAGE,
      });
      setRows(res.data ?? []);
      setMeta(res.meta);
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Erro ao carregar banco de pontos.";
      toast.error(msg);
      setRows([]);
    } finally {
      setLoading(false);
    }
  }, [estaAtivo, buscaDebounced, page]);

  useEffect(() => {
    const t = window.setTimeout(() => setBuscaDebounced(buscaInput), 350);
    return () => window.clearTimeout(t);
  }, [buscaInput]);

  useEffect(() => {
    setPage(1);
  }, [estaAtivo, buscaDebounced]);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <div className="flex h-full flex-col bg-background pb-16 md:pb-0">
      <div className="border-b border-border bg-muted/20 p-3 md:p-6">
        <div>
          <h1 className="flex items-center gap-2 text-xl font-bold text-foreground md:text-3xl">
            <Landmark className="h-5 w-5 md:h-6 md:w-6" />
            Banco de Pontos
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Lista de parceiros e saldo; use Detalhes para ver o extrato completo.
          </p>
        </div>
      </div>

      <div className="flex flex-1 flex-col gap-4 p-3 md:p-6">
        <div className="flex flex-col gap-3 rounded-lg border border-border/80 bg-card/50 p-4 md:flex-row md:flex-wrap md:items-end">
          <div className="min-w-[200px] flex-1 space-y-2">
            <Label htmlFor="banco-busca">Buscar parceiro</Label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                id="banco-busca"
                className="pl-9"
                placeholder="Nome ou codinome..."
                value={buscaInput}
                onChange={(e) => setBuscaInput(e.target.value)}
              />
            </div>
          </div>
          <div className="w-full space-y-2 md:w-48">
            <Label>Status</Label>
            <Select value={estaAtivo} onValueChange={(v) => setEstaAtivo(v as BancoPontosEstaAtivoFiltro)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos</SelectItem>
                <SelectItem value="true">Ativos</SelectItem>
                <SelectItem value="false">Inativos</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="overflow-x-auto rounded-lg border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[88px]">Foto</TableHead>
                <TableHead className="min-w-[220px]">Nome</TableHead>
                <TableHead className="min-w-[120px] text-right">Saldo</TableHead>
                <TableHead className="w-[140px] text-center">Detalhes</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={4} className="py-14 text-center text-muted-foreground">
                    <Loader2 className="mx-auto mb-2 h-8 w-8 animate-spin text-primary" />
                    Carregando parceiros...
                  </TableCell>
                </TableRow>
              ) : rows.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={4} className="py-12 text-center text-muted-foreground">
                    <Building2 className="mx-auto mb-2 h-10 w-10 opacity-40" />
                    Nenhum parceiro encontrado com os filtros atuais.
                  </TableCell>
                </TableRow>
              ) : (
                rows.map((row) => (
                  <TableRow key={row.parceiroId}>
                    <TableCell>
                      <ParceiroFotoCell
                        key={row.parceiroId}
                        nome={row.nome}
                        logoUrl={row.logoUrl}
                        fotoUrl={row.fotoUrl}
                      />
                    </TableCell>
                    <TableCell className="font-medium">{getDisplayNome(row)}</TableCell>
                    <TableCell
                      className={`text-right font-semibold tabular-nums ${
                        Number(row.saldo) >= 0 ? "text-emerald-600" : "text-red-600"
                      }`}
                    >
                      {formatPontos(Number(row.saldo))}
                    </TableCell>
                    <TableCell className="text-center">
                      <Button
                        size="sm"
                        variant="outline"
                        className="border-border bg-background text-foreground hover:bg-muted/50 hover:text-foreground"
                        onClick={() =>
                          navigate(`/fechamento/banco-pontos/${row.parceiroId}`, {
                            state: { nomeExibicao: getDisplayNome(row) },
                          })
                        }
                      >
                        Detalhes
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>

        {!loading && meta.totalPaginas > 1 ? (
          <div className="flex flex-wrap items-center justify-between gap-3 border-t pt-2">
            <p className="text-sm text-muted-foreground">
              Página {meta.paginaAtual} de {meta.totalPaginas}
            </p>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                disabled={page <= 1}
                onClick={() => setPage((p) => Math.max(1, p - 1))}
              >
                <ChevronLeft className="h-4 w-4" />
                Anterior
              </Button>
              <Button
                variant="outline"
                size="sm"
                disabled={page >= meta.totalPaginas}
                onClick={() => setPage((p) => Math.min(meta.totalPaginas, p + 1))}
              >
                Próxima
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );
}
