import React, { useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Search } from "lucide-react";

import { OcBookAPI } from "@/apis/OcBookAPI";
import { Badge } from "@/components/ui/badge";
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useCompanyStore } from "@/hooks/store/useCompanyStore";
import { createPanelPageUrl } from "@/utils";
import { OC_BOOK_MONTH_OPTIONS, ocBookMonthYearToRange, ocBookYearOptions } from "@/utils/ocBookPeriod";

const badgeClassByStatus = {
  pending_validation: "bg-orange-100 text-orange-700 hover:bg-orange-100",
  validated: "bg-sky-100 text-sky-700 hover:bg-sky-100",
};

export default function OCBookValidation() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { selectedCompany } = useCompanyStore();
  const companyId = String(selectedCompany?.id ?? "");

  const monthQ = searchParams.get("month") ?? "";
  const yearQ = searchParams.get("year") ?? "";
  const hasPeriod = Boolean(monthQ && yearQ);

  const currentYear = new Date().getFullYear();
  const yearOptions = useMemo(() => ocBookYearOptions(currentYear, 3), [currentYear]);

  const [gateMonth, setGateMonth] = useState(String(new Date().getMonth() + 1));
  const [gateYear, setGateYear] = useState(String(currentYear));

  const [draftFrom, setDraftFrom] = useState("");
  const [draftTo, setDraftTo] = useState("");
  const [draftStatus, setDraftStatus] = useState("all");
  const [appliedFilters, setAppliedFilters] = useState({});
  const [searchText, setSearchText] = useState("");
  const [selectedOrderId, setSelectedOrderId] = useState(null);

  useEffect(() => {
    if (hasPeriod) {
      const { date_from, date_to } = ocBookMonthYearToRange(yearQ, monthQ);
      setDraftFrom(date_from);
      setDraftTo(date_to);
      setDraftStatus("all");
      setAppliedFilters({
        ...(date_from ? { date_from } : {}),
        ...(date_to ? { date_to } : {}),
      });
    }
  }, [hasPeriod, monthQ, yearQ]);

  const apiParams = useMemo(() => {
    const p = { ...appliedFilters };
    if (p.status === "all") {
      delete p.status;
    }
    return p;
  }, [appliedFilters]);

  const validationQuery = useQuery({
    queryKey: ["oc-book-validation", companyId, apiParams],
    queryFn: () => OcBookAPI.getValidation(companyId, apiParams),
    enabled: Boolean(companyId && hasPeriod),
  });

  const rowsRaw = validationQuery.data?.rows ?? [];
  const summary = validationQuery.data?.summary ?? {};

  const rows = useMemo(() => {
    const t = searchText.trim().toLowerCase();
    if (!t) return rowsRaw;
    return rowsRaw.filter((row) => {
      const blob = [row.folio, row.document_type, row.supplier_rut, row.supplier_name, row.requested_by, row.emission_date]
        .map((x) => String(x ?? "").toLowerCase())
        .join(" ");
      return blob.includes(t);
    });
  }, [rowsRaw, searchText]);

  const periodTitle = useMemo(() => {
    if (!hasPeriod) return "";
    const m = OC_BOOK_MONTH_OPTIONS.find((o) => o.value === monthQ);
    return `${m?.label ?? ""} del ${yearQ}`;
  }, [hasPeriod, monthQ, yearQ]);

  const handleConsultar = () => {
    router.push(createPanelPageUrl(`oc/book/validation?month=${gateMonth}&year=${gateYear}`));
  };

  const handleVolver = () => {
    router.push(createPanelPageUrl("oc/book/validation"));
  };

  const handleApplyFilters = () => {
    const next = {
      ...(draftFrom ? { date_from: draftFrom } : {}),
      ...(draftTo ? { date_to: draftTo } : {}),
    };
    if (draftStatus && draftStatus !== "all") {
      next.status = draftStatus;
    }
    setAppliedFilters(next);
  };

  if (!hasPeriod) {
    return (
      <div className="p-4 lg:p-8 space-y-8">
        <div>
          <h1 className="text-3xl font-bold text-gradient">Validación de órdenes de compra</h1>
          <p className="text-gray-600 mt-1">Seleccione el mes y período a consultar el estado de OC.</p>
        </div>

        <Card className="glass-card border-white/20 max-w-3xl">
          <CardContent className="p-6 flex flex-col sm:flex-row flex-wrap items-end gap-4">
            <div className="space-y-1 min-w-[160px]">
              <Label>Mes</Label>
              <Select value={gateMonth} onValueChange={setGateMonth}>
                <SelectTrigger className="bg-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {OC_BOOK_MONTH_OPTIONS.map((m) => (
                    <SelectItem key={m.value} value={m.value}>
                      {m.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1 min-w-[140px]">
              <Label>Período</Label>
              <Select value={gateYear} onValueChange={setGateYear}>
                <SelectTrigger className="bg-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {yearOptions.map((y) => (
                    <SelectItem key={y} value={y}>
                      {y}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <Button className="bg-blue-600 hover:bg-blue-700 sm:ml-auto" onClick={handleConsultar} disabled={!companyId}>
              Consultar
            </Button>
          </CardContent>
        </Card>

        {!companyId ? (
          <p className="text-sm text-amber-800 bg-amber-50 border border-amber-200 rounded-lg p-3 max-w-3xl">
            Seleccione una empresa para continuar.
          </p>
        ) : null}
      </div>
    );
  }

  return (
    <div className="p-4 lg:p-8 space-y-8">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gradient">Validación de orden de compra</h1>
          <p className="text-gray-600 mt-1">
            {selectedCompany?.name} • {periodTitle}
          </p>
        </div>
        <Button variant="outline" className="shrink-0 border-blue-200 text-blue-700 hover:bg-blue-50" onClick={handleVolver}>
          Volver
        </Button>
      </div>

      <div className="grid gap-4 lg:grid-cols-5">
        <Card className="glass-card border-white/20 lg:col-span-3">
          <CardContent className="p-4 space-y-4">
            <h2 className="text-base font-semibold text-slate-800 border-b border-slate-100 pb-2">Filtros</h2>
            <div className="grid sm:grid-cols-3 gap-3 items-end">
              <div className="space-y-1 sm:col-span-2">
                <Label>Fecha</Label>
                <div className="flex flex-col sm:flex-row gap-2">
                  <Input type="date" className="bg-white" value={draftFrom} onChange={(e) => setDraftFrom(e.target.value)} />
                  <Input type="date" className="bg-white" value={draftTo} onChange={(e) => setDraftTo(e.target.value)} />
                </div>
              </div>
              <div className="space-y-1">
                <Label>Estado</Label>
                <Select value={draftStatus} onValueChange={setDraftStatus}>
                  <SelectTrigger className="bg-white">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Todos</SelectItem>
                    <SelectItem value="pending_validation">Pendientes de validación</SelectItem>
                    <SelectItem value="validated">Validadas</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <Button type="button" className="bg-blue-600 hover:bg-blue-700" onClick={handleApplyFilters}>
              Aplicar filtros
            </Button>
          </CardContent>
        </Card>

        <Card className="glass-card border-white/20 lg:col-span-2">
          <CardContent className="p-4 space-y-3">
            <h2 className="text-base font-semibold text-slate-800 border-b border-slate-100 pb-2">Resumen</h2>
            <div className="space-y-3 text-sm">
              <div className="flex justify-between gap-4">
                <span className="text-gray-600">En validación</span>
                <span className="text-xl font-bold">{summary.in_flow ?? 0}</span>
              </div>
              <div className="flex justify-between gap-4">
                <span className="text-gray-600">Pendientes de validación</span>
                <span className="text-xl font-bold">{summary.pending_validation ?? 0}</span>
              </div>
              <div className="flex justify-between gap-4">
                <span className="text-gray-600">Validadas</span>
                <span className="text-xl font-bold">{summary.validated ?? 0}</span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <Card className="glass-card border-white/20">
        <CardContent className="p-4 space-y-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <h2 className="text-lg font-semibold">Libro de órdenes de compra</h2>
            <div className="relative max-w-md w-full">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <Input
                className="pl-9 bg-white"
                placeholder="Buscar por folio, RUT, proveedor..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
              />
            </div>
          </div>
          <div className="overflow-auto rounded-xl border border-slate-100">
            <table className="w-full min-w-[1000px]">
              <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</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">Total</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Estado OC</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600 sticky right-0 bg-slate-50 z-10 min-w-[140px] shadow-[-6px_0_12px_-6px_rgba(15,23,42,0.12)]">
                    Acciones
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {validationQuery.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}>
                      No hay órdenes para los filtros seleccionados.
                    </td>
                  </tr>
                ) : (
                  rows.map((row) => (
                    <tr key={row.id} className="group bg-white hover:bg-slate-50/80">
                      <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 != null && 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">
                        <Badge
                          className={
                            badgeClassByStatus[row.status] ?? "bg-slate-100 text-slate-700 hover:bg-slate-100"
                          }
                        >
                          {row.status === "pending_validation" ? "Pendiente validación" : "Validada"}
                        </Badge>
                      </td>
                      <td className="p-3 sticky right-0 z-10 bg-white group-hover:bg-slate-50/80 min-w-[140px] shadow-[-6px_0_12px_-6px_rgba(15,23,42,0.1)]">
                        <Button size="sm" className="bg-blue-600 hover:bg-blue-700" onClick={() => setSelectedOrderId(String(row.id))}>
                          Ir a validar
                        </Button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      <Dialog open={Boolean(selectedOrderId)} onOpenChange={(open) => !open && setSelectedOrderId(null)}>
        <DialogContent className="sm:max-w-[480px]">
          <DialogHeader>
            <DialogTitle>Validación de orden de compra</DialogTitle>
            <DialogDescription>
              Va a abrir el detalle de validación de esta orden. ¿Desea continuar?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setSelectedOrderId(null)}>
              Cancelar
            </Button>
            <Button
              onClick={() => {
                if (!selectedOrderId) return;
                router.push(createPanelPageUrl(`oc/book/validation/${selectedOrderId}`));
              }}
            >
              Sí, ingresar
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
