// pages/abastecimentos/consulta_abastecimento.tsx
'use client';

import { useState, useEffect, useRef } from "react";
import { createClientComponentClient } from "@supabase/auth-helpers-nextjs";
import {
  Table, TableHeader, TableBody, TableRow, TableHead, TableCell
} from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import dayjs from "dayjs";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";

type Truck = { id: string; placa: string };
type Employee = { id: string; nome: string };
type Refuel = {
  id: string;
  id_truck: string;
  id_funcionario: string | null;
  quilometragem: number;
  litros: number;
  data_abastecimento: string;
};
type Maintenance = { id_truck: string; status: string };
type Policy = { id_relacionado: string; status: string; data_fim: string | null };

export default function ConsultaAbastecimento() {
  const supabase = createClientComponentClient();
  const reportRef = useRef<HTMLDivElement>(null);

  const [trucks, setTrucks] = useState<Truck[]>([]);
  const [employees, setEmployees] = useState<Record<string,string>>({});
  const [maintStatus, setMaintStatus] = useState<Record<string,string>>({});
  const [polStatus, setPolStatus] = useState<Record<string,string>>({});
  const [refuels, setRefuels] = useState<Refuel[]>([]);

  const [truckFilter, setTruckFilter] = useState<string>("");
  const [fromDate, setFromDate] = useState<string>(dayjs().startOf('month').format('YYYY-MM-DD'));
  const [toDate, setToDate] = useState<string>(dayjs().format('YYYY-MM-DD'));

  // Carrega dropdowns e status
  useEffect(() => {
    supabase.from<Truck>("trucks").select("id, placa")
      .then(({ data }) => setTrucks(data || []));
    supabase.from<Employee>("employees").select("id, nome")
      .then(({ data }) => {
        const map: Record<string,string> = {};
        data?.forEach(e => map[e.id] = e.nome);
        setEmployees(map);
      });
    supabase.from<Maintenance>("truck_maintenance").select("id_truck, status")
      .then(({ data }) => {
        const map: Record<string,string> = {};
        data?.forEach(m => {
          if (m.status !== "Concluída") map[m.id_truck] = "Pendente";
        });
        setMaintStatus(map);
      });
    supabase.from<Policy>("insurance_policies").select("id_relacionado, status, data_fim")
      .then(({ data }) => {
        const map: Record<string,string> = {};
        const hoje = dayjs();
        data?.forEach(p => {
          if (p.status === "Ativa" && p.data_fim && dayjs(p.data_fim).isAfter(hoje))
            map[p.id_relacionado] = "Válida";
        });
        setPolStatus(map);
      });
  }, []);

  // Busca os dados sempre que filtros mudam
  async function fetchData() {
    const { data } = await supabase
      .from<Refuel>("truck_refuels")
      .select("*")
      .gte("data_abastecimento", fromDate)
      .lte("data_abastecimento", toDate)
      .order("data_abastecimento", { ascending: true });
    setRefuels(data || []);
  }
  useEffect(fetchData, [truckFilter, fromDate, toDate]);

  // Agrupa e resume
  const summary = trucks
    .filter(t => !truckFilter || t.id === truckFilter)
    .map(t => {
      const recs = refuels.filter(r => r.id_truck === t.id);
      if (!recs.length) return null;
      const kmIni = recs[0].quilometragem;
      const kmFim = recs[recs.length - 1].quilometragem;
      const dist = kmFim - kmIni;
      const litrosTot = recs.reduce((s, r) => s + r.litros, 0);
      return {
        placa: t.placa,
        motorista: employees[recs[recs.length - 1].id_funcionario || ""] || "—",
        kmTotal: kmFim,
        distancia: dist,
        litrosTot: litrosTot.toFixed(2),
        media: dist > 0 ? (litrosTot/dist).toFixed(2) : "—",
        manut: maintStatus[t.id] || "OK",
        seguro: polStatus[t.id] || "—",
      };
    })
    .filter(Boolean) as any[];

  // Imprimir
  const handlePrint = () => {
    window.print();
  };

  // Exportar PDF
  const handleExportPdf = async () => {
    if (!reportRef.current) return;
    const canvas = await html2canvas(reportRef.current);
    const imgData = canvas.toDataURL("image/png");
    const pdf = new jsPDF("landscape", "mm", "a4");
    const pdfWidth = pdf.internal.pageSize.getWidth();
    const pdfHeight = (canvas.height * pdfWidth) / canvas.width;
    pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight);
    pdf.save("relatorio_abastecimento.pdf");
  };

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-6">
      <h1 className="text-3xl font-bold">Consulta de Abastecimentos</h1>

      {/* Filtros */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Select value={truckFilter} onValueChange={setTruckFilter}>
          <Select.Trigger><Select.Value placeholder="Todos Caminhões" /></Select.Trigger>
          <Select.Content>
            <Select.Item value="">Todos</Select.Item>
            {trucks.map(t => (
              <Select.Item key={t.id} value={t.id}>{t.placa}</Select.Item>
            ))}
          </Select.Content>
        </Select>
        <Input type="date" value={fromDate} onChange={e => setFromDate(e.target.value)} />
        <Input type="date" value={toDate} onChange={e => setToDate(e.target.value)} />
        <Button onClick={fetchData}>Filtrar</Button>
      </div>

      {/* Botões de ação */}
      <div className="flex gap-2">
        <Button onClick={handlePrint} variant="outline">🖨️ Imprimir</Button>
        <Button onClick={handleExportPdf} variant="outline">📄 Exportar PDF</Button>
      </div>

      {/* Relatório */}
      <div ref={reportRef}>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Caminhão</TableHead>
              <TableHead>Motorista</TableHead>
              <TableHead>KM Total</TableHead>
              <TableHead>Distância (km)</TableHead>
              <TableHead>Litros</TableHead>
              <TableHead>Consumo (L/km)</TableHead>
              <TableHead>Status Manut.</TableHead>
              <TableHead>Status Seguro</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {summary.map((s, i) => (
              <TableRow key={i}>
                <TableCell>{s.placa}</TableCell>
                <TableCell>{s.motorista}</TableCell>
                <TableCell>{s.kmTotal}</TableCell>
                <TableCell>{s.distancia}</TableCell>
                <TableCell>{s.litrosTot}</TableCell>
                <TableCell>{s.media}</TableCell>
                <TableCell>
                  <Badge variant={s.manut === "OK" ? "success" : "destructive"}>
                    {s.manut}
                  </Badge>
                </TableCell>
                <TableCell>
                  <Badge variant={s.seguro === "Válida" ? "success" : "warning"}>
                    {s.seguro}
                  </Badge>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
