import { useMemo, useState } from "react";
import { Head, Link, router } from "@inertiajs/react";
import axios from "axios";
import { toast } from "sonner";
import { FileText, Settings, Eye, CheckCircle2, AlertTriangle, Loader2, ChevronLeft, ChevronRight, Send, Download, Users, Clock } from "lucide-react";
import AppLayout from "@/Layouts/AppLayout";
import PageHeader from "@/Components/PageHeader";
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/Components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/Components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/Components/ui/dialog";
import { Card, CardContent } from "@/Components/ui/card";

const CADENCE_LABEL = { semanal: "Semanal", mensal: "Mensal" };
const ITEMS_PER_PAGE = 10;

// Estado de entrega -> rótulo + ícone (padrão de status badges do CLAUDE.md).
function DeliveryStatus({ status, deliveredAt }) {
  const map = {
    not_sent: { icon: <Clock className="h-3 w-3 text-muted-foreground/60" />, label: "Não enviado" },
    queued:   { icon: <Loader2 className="h-3 w-3 animate-spin" />, label: "Na fila" },
    sending:  { icon: <Loader2 className="h-3 w-3 animate-spin" />, label: "Enviando..." },
    sent:     { icon: <CheckCircle2 className="h-3.5 w-3.5 fill-emerald-500 text-white dark:text-background" />, label: "Enviado" },
    partial:  { icon: <AlertTriangle className="h-3 w-3 text-amber-500" />, label: "Parcial" },
    failed:   { icon: <AlertTriangle className="h-3 w-3 text-destructive" />, label: "Falhou" },
  };
  const s = map[status] ?? map.not_sent;
  return (
    <span className="inline-flex items-center gap-1 text-xs text-muted-foreground" title={deliveredAt ? `Em ${deliveredAt}` : undefined}>
      {s.icon}
      {s.label}
    </span>
  );
}

function fmtDate(d) {
  if (!d) return "-";
  const [y, m, day] = d.split("-");
  return `${day}/${m}/${y}`;
}

function fmtDateTime(iso) {
  if (!iso) return "-";
  return new Date(iso).toLocaleString("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

export default function RelatoriosLista({ project = null, runs = [] }) {
  const [cadenceFilter, setCadenceFilter] = useState("all");
  const [page, setPage] = useState(1);
  const [sendingId, setSendingId] = useState(null);
  const [deliveries, setDeliveries] = useState(null); // { label, loading, rows }

  function sendRun(r) {
    const isResend = ["sent", "partial", "failed"].includes(r.delivery_status);
    router.post(
      route("relatorios.runs.send", [project.id, r.id]),
      {},
      {
        preserveScroll: true,
        onStart: () => setSendingId(r.id),
        onFinish: () => setSendingId(null),
        onSuccess: () => toast.success(isResend ? "Reenvio enfileirado." : "Envio enfileirado."),
        onError: () => toast.error("Não foi possível enfileirar o envio."),
      }
    );
  }

  async function openDeliveries(r) {
    setDeliveries({ label: `${CADENCE_LABEL[r.cadence] ?? r.cadence} · ${fmtDate(r.period_start)} - ${fmtDate(r.period_end)}`, loading: true, rows: [] });
    try {
      const { data } = await axios.get(route("relatorios.runs.deliveries", [project.id, r.id]));
      setDeliveries((d) => ({ ...d, loading: false, rows: data.deliveries ?? [] }));
    } catch {
      setDeliveries((d) => ({ ...d, loading: false, rows: [] }));
      toast.error("Não foi possível carregar as entregas.");
    }
  }

  const filtered = useMemo(() => {
    return runs.filter((r) => cadenceFilter === "all" || r.cadence === cadenceFilter);
  }, [runs, cadenceFilter]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / ITEMS_PER_PAGE));
  const currentPage = Math.min(page, totalPages);
  const pageRows = filtered.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  if (!project) {
    return (
      <AppLayout>
        <Head title="Relatórios" />
        <div className="mx-auto flex w-full max-w-[1100px] flex-col gap-4">
          <PageHeader title="Relatórios" />
          <Card>
            <CardContent className="flex flex-col items-center justify-center gap-2 py-16 text-center text-muted-foreground">
              <FileText className="h-8 w-8" />
              <p>Selecione um projeto no seletor acima.</p>
            </CardContent>
          </Card>
        </div>
      </AppLayout>
    );
  }

  return (
    <AppLayout>
      <Head title={`Relatórios - ${project.name}`} />
      <div className="mx-auto flex w-full max-w-[1100px] flex-col gap-4">
        <PageHeader title="Relatórios gerados">
          <Button variant="outline" asChild className="w-full sm:w-auto">
            <Link href={route("relatorios.config", project.id)}>
              <Settings className="h-4 w-4" />
              Configurar relatórios
            </Link>
          </Button>
        </PageHeader>

        <p className="-mt-2 text-sm text-muted-foreground">
          {project.name} · {runs.length} relatório{runs.length === 1 ? "" : "s"} gerado
          {runs.length === 1 ? "" : "s"}
        </p>

        {/* Filtro */}
        <div className="flex flex-col gap-2 sm:flex-row">
          <Select
            value={cadenceFilter}
            onValueChange={(v) => {
              setCadenceFilter(v);
              setPage(1);
            }}
          >
            <SelectTrigger className="w-full sm:w-44">
              <SelectValue placeholder="Ciclo" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Todos os ciclos</SelectItem>
              <SelectItem value="semanal">Semanal</SelectItem>
              <SelectItem value="mensal">Mensal</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {runs.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center gap-2 py-16 text-center text-muted-foreground">
              <FileText className="h-8 w-8" />
              <p>Nenhum relatório gerado ainda.</p>
              <Button variant="outline" asChild>
                <Link href={route("relatorios.config", project.id)}>
                  Ir para a configuração
                </Link>
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Ciclo</TableHead>
                  <TableHead>Período</TableHead>
                  <TableHead className="hidden sm:table-cell">Gerado em</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="hidden md:table-cell">Entrega</TableHead>
                  <TableHead className="text-right">Ações</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {pageRows.map((r) => (
                  <TableRow key={r.id}>
                    <TableCell>
                      <Badge
                        variant="outline"
                        className="rounded-full px-1.5 font-normal text-muted-foreground"
                      >
                        {CADENCE_LABEL[r.cadence] ?? r.cadence}
                      </Badge>
                    </TableCell>
                    <TableCell className="tabular-nums">
                      {fmtDate(r.period_start)} - {fmtDate(r.period_end)}
                    </TableCell>
                    <TableCell className="hidden tabular-nums sm:table-cell">
                      {fmtDateTime(r.generated_at)}
                    </TableCell>
                    <TableCell>
                      {r.status === "success" ? (
                        <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                          <CheckCircle2 className="h-3.5 w-3.5 fill-emerald-500 text-white dark:text-background" />
                          Gerado
                        </span>
                      ) : r.status === "generating" ? (
                        <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                          <Loader2 className="h-3 w-3 animate-spin" />
                          Gerando...
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                          <AlertTriangle className="h-3 w-3 text-destructive" />
                          Erro
                        </span>
                      )}
                    </TableCell>
                    <TableCell className="hidden md:table-cell">
                      <DeliveryStatus status={r.delivery_status} deliveredAt={fmtDateTime(r.delivered_at)} />
                    </TableCell>
                    <TableCell className="text-right">
                      {r.status === "success" && (
                        <div className="flex items-center justify-end gap-0.5">
                          <Button variant="ghost" size="icon" className="h-8 w-8" asChild title="Ver relatório">
                            <Link href={route("relatorios.runs.show", [project.id, r.id])}>
                              <Eye className="h-4 w-4" />
                            </Link>
                          </Button>

                          {r.pdf_status === "done" && (
                            <Button variant="ghost" size="icon" className="h-8 w-8" asChild title="Baixar PDF">
                              <a href={route("relatorios.runs.pdf", [project.id, r.id])} target="_blank" rel="noopener noreferrer">
                                <Download className="h-4 w-4" />
                              </a>
                            </Button>
                          )}

                          {r.delivery_status !== "not_sent" && (
                            <Button variant="ghost" size="icon" className="h-8 w-8" title="Ver entregas" onClick={() => openDeliveries(r)}>
                              <Users className="h-4 w-4" />
                            </Button>
                          )}

                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8"
                            title={["sent", "partial", "failed"].includes(r.delivery_status) ? "Reenviar" : "Enviar"}
                            disabled={sendingId === r.id || ["queued", "sending"].includes(r.delivery_status)}
                            onClick={() => sendRun(r)}
                          >
                            {sendingId === r.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
                          </Button>
                        </div>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}

        {/* Paginação */}
        {filtered.length > ITEMS_PER_PAGE && (
          <div className="flex items-center justify-end gap-2">
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={currentPage === 1}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="px-2 text-sm">
              {currentPage} / {totalPages}
            </span>
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        )}

        {/* Detalhe de entregas por destinatário */}
        <Dialog open={!!deliveries} onOpenChange={(o) => !o && setDeliveries(null)}>
          <DialogContent className="max-w-lg">
            <DialogHeader>
              <DialogTitle>Entregas</DialogTitle>
              <DialogDescription>{deliveries?.label}</DialogDescription>
            </DialogHeader>
            {deliveries?.loading ? (
              <div className="flex items-center justify-center gap-2 py-8 text-sm text-muted-foreground">
                <Loader2 className="h-4 w-4 animate-spin" /> Carregando...
              </div>
            ) : deliveries?.rows?.length ? (
              <div className="max-h-[60vh] overflow-auto rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Destinatário</TableHead>
                      <TableHead>Status</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {deliveries.rows.map((d) => (
                      <TableRow key={d.email}>
                        <TableCell>
                          <div className="text-sm">{d.name || d.email}</div>
                          {d.name && <div className="text-xs text-muted-foreground">{d.email}</div>}
                          {d.error && <div className="text-xs text-destructive">{d.error}</div>}
                        </TableCell>
                        <TableCell>
                          {d.status === "sent" ? (
                            <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                              <CheckCircle2 className="h-3.5 w-3.5 fill-emerald-500 text-white dark:text-background" />
                              Enviado
                            </span>
                          ) : d.status === "failed" ? (
                            <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                              <AlertTriangle className="h-3 w-3 text-destructive" /> Falhou
                            </span>
                          ) : (
                            <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                              <Clock className="h-3 w-3" /> Pendente
                            </span>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <p className="py-8 text-center text-sm text-muted-foreground">Nenhuma entrega registrada.</p>
            )}
          </DialogContent>
        </Dialog>
      </div>
    </AppLayout>
  );
}
