import React, { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";

import { OcBookAPI } from "@/apis/OcBookAPI";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useCompanyStore } from "@/hooks/store/useCompanyStore";

export default function OCSectorizedAuthorization() {
  const queryClient = useQueryClient();
  const { selectedCompany } = useCompanyStore();
  const companyId = String(selectedCompany?.id ?? "");
  const [search, setSearch] = useState("");
  const [selectedOrder, setSelectedOrder] = useState(null);

  const listQuery = useQuery({
    queryKey: ["oc-sectorized-authorizations", companyId, search],
    queryFn: () => OcBookAPI.getSectorizedAuthorizations(companyId, { search: search.trim() || undefined }),
    enabled: Boolean(companyId),
  });

  const authorizeMutation = useMutation({
    mutationFn: () => OcBookAPI.approveSectorizedAuthorization(companyId, String(selectedOrder?.id ?? "")),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["oc-sectorized-authorizations", companyId] });
      await queryClient.invalidateQueries({ queryKey: ["oc-sectorized-panel", companyId] });
      await queryClient.invalidateQueries({ queryKey: ["oc-book-tracking", companyId] });
      await queryClient.invalidateQueries({ queryKey: ["oc-book-validation", companyId] });
      await queryClient.invalidateQueries({ queryKey: ["oc-book-match-orders", companyId] });
      setSelectedOrder(null);
      toast.success("Orden autorizada para inventario sectorizado.");
    },
    onError: () => toast.error("No se pudo autorizar la orden."),
  });

  const rows = useMemo(() => listQuery.data ?? [], [listQuery.data]);

  return (
    <div className="p-4 lg:p-8 space-y-8">
      <div>
        <h1 className="text-3xl font-bold text-gradient">Autorización de Ingreso a Inventario Sectorizado</h1>
        <p className="text-gray-600 mt-1">
          Autorice el ingreso de órdenes de compra al proceso de Inventario Sectorizado.
        </p>
      </div>

      <Card className="glass-card border-white/20">
        <CardContent className="p-4 space-y-4">
          <h2 className="text-lg font-semibold">Libro de Órdenes de Compra</h2>
          <div className="grid sm:grid-cols-[1fr_auto] gap-3 items-end">
            <div className="space-y-1">
              <Label>Buscar</Label>
              <Input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Folio, RUT, razón social, solicitado por..."
                className="bg-white"
              />
            </div>
          </div>
          <div className="overflow-auto rounded-xl border border-slate-100">
            <table className="w-full min-w-[980px]">
              <thead className="bg-slate-50">
                <tr>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Fecha</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Folio (Tipo Doc.)</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Rut</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Razón Social</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Solicitado por</th>
                  <th className="p-3 text-right text-xs font-semibold text-slate-600">Monto</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Estado</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Acciones</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {listQuery.isLoading ? (
                  <tr>
                    <td className="p-4 text-center text-gray-600" colSpan={8}>
                      Cargando...
                    </td>
                  </tr>
                ) : rows.length === 0 ? (
                  <tr>
                    <td className="p-4 text-center text-gray-600" colSpan={8}>
                      Sin registros.
                    </td>
                  </tr>
                ) : (
                  rows.map((row) => (
                    <tr key={String(row.id)}>
                      <td className="p-3 text-sm whitespace-nowrap">{row.emission_date ?? "—"}</td>
                      <td className="p-3 text-sm whitespace-nowrap">
                        {row.folio ?? "—"} {row.document_type ? `(${row.document_type})` : ""}
                      </td>
                      <td className="p-3 text-sm whitespace-nowrap">{row.supplier_rut ?? "—"}</td>
                      <td className="p-3 text-sm">{row.supplier_name ?? "—"}</td>
                      <td className="p-3 text-sm">{row.requested_by ?? "—"}</td>
                      <td className="p-3 text-right text-sm whitespace-nowrap">
                        ${Number(row.total ?? 0).toLocaleString("es-CL")}
                      </td>
                      <td className="p-3 text-sm">
                        <span className="inline-flex items-center rounded-full bg-orange-100 px-2 py-0.5 text-xs font-medium text-orange-700">
                          Pendiente
                        </span>
                      </td>
                      <td className="p-3">
                        <Button size="sm" variant="outline" onClick={() => setSelectedOrder(row)}>
                          Autorizar
                        </Button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      <Dialog open={Boolean(selectedOrder)} onOpenChange={(open) => !open && setSelectedOrder(null)}>
        <DialogContent className="sm:max-w-[540px]">
          <DialogHeader>
            <DialogTitle>¿Autorizar ingreso al Inventario Sectorizado?</DialogTitle>
            <DialogDescription>
              La orden quedará habilitada para proceso de imputación de inventario.
            </DialogDescription>
          </DialogHeader>
          <div className="text-sm space-y-1">
            <p>
              <span className="font-semibold">OC:</span> {selectedOrder?.folio ?? "—"}
            </p>
            <p>
              <span className="font-semibold">Proveedor:</span> {selectedOrder?.supplier_name ?? "—"}
            </p>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setSelectedOrder(null)}>
              Cancelar
            </Button>
            <Button
              className="bg-blue-600 hover:bg-blue-700"
              onClick={() => authorizeMutation.mutate()}
              disabled={authorizeMutation.isPending}
            >
              {authorizeMutation.isPending ? "Autorizando..." : "Autorizar"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
