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

import { OcBookAPI } from "@/apis/OcBookAPI";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
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 STATUS_LABELS = {
  issued: "Emitida",
  pending_validation: "Pendiente validación",
  validated: "Validada",
  paid: "Pagada",
  accounted: "Contabilizada",
  inventoried: "Inventariada",
};

const STATUS_RANK = {
  issued: 1,
  pending_validation: 2,
  validated: 3,
  paid: 4,
  accounted: 5,
  inventoried: 6,
};

const rankOf = (status) => STATUS_RANK[String(status)] ?? 0;

/** @param {string | undefined} status */
const showPaidOk = (status) => rankOf(status) >= STATUS_RANK.paid;
/** @param {string | undefined} status */
const showAccountedOk = (status) => rankOf(status) >= STATUS_RANK.accounted;
/** @param {string | undefined} status */
const showInventoryOk = (status) => rankOf(status) >= STATUS_RANK.inventoried;

export default function OCBookTracking() {
  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 [appliedFilters, setAppliedFilters] = useState({});
  const [status, setStatus] = useState("all");
  const [searchText, setSearchText] = useState("");

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

  const apiParams = useMemo(
    () => ({
      ...appliedFilters,
    }),
    [appliedFilters],
  );

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

  const rowsRaw = useMemo(() => {
    const source = trackingQuery.data?.rows ?? [];
    if (status === "all") return source;
    return source.filter((row) => row.status === status);
  }, [trackingQuery.data?.rows, status]);

  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.invoice_folio,
        row.invoice_document_type,
        row.emission_date,
      ]
        .map((x) => String(x ?? "").toLowerCase())
        .join(" ");
      return blob.includes(t);
    });
  }, [rowsRaw, searchText]);

  const summary = trackingQuery.data?.summary ?? {};

  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/tracking?month=${gateMonth}&year=${gateYear}`));
  };

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

  const handleApplyFilters = () => {
    setAppliedFilters({
      ...(draftFrom ? { date_from: draftFrom } : {}),
      ...(draftTo ? { date_to: draftTo } : {}),
    });
  };

  if (!hasPeriod) {
    return (
      <div className="p-4 lg:p-8 space-y-8">
        <div>
          <h1 className="text-3xl font-bold text-gradient">Libro de órdenes de compra</h1>
          <p className="text-gray-600 mt-1">Seleccione el mes y período a consultar el seguimiento 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 consultar el libro OC.
          </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">Seguimiento 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>Rango de fechas (emisión OC)</Label>
                <div className="flex flex-col xs: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={status} onValueChange={setStatus}>
                  <SelectTrigger className="bg-white">
                    <SelectValue placeholder="Todos" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Todos</SelectItem>
                    <SelectItem value="issued">Emitida</SelectItem>
                    <SelectItem value="pending_validation">Pendiente validación</SelectItem>
                    <SelectItem value="validated">Validada</SelectItem>
                    <SelectItem value="paid">Pagada</SelectItem>
                    <SelectItem value="accounted">Contabilizada</SelectItem>
                    <SelectItem value="inventoried">Inventariada</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 del período</h2>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <p className="text-gray-600">Emitidas</p>
                <p className="text-2xl font-bold">{summary.total_in_period ?? 0}</p>
              </div>
              <div>
                <p className="text-gray-600">Pagadas</p>
                <p className="text-2xl font-bold">{summary.paid ?? 0}</p>
              </div>
              <div>
                <p className="text-gray-600">Contabilizadas</p>
                <p className="text-2xl font-bold">{summary.accounted ?? 0}</p>
              </div>
              <div>
                <p className="text-gray-600">Inventariadas</p>
                <p className="text-2xl font-bold">{summary.inventoried ?? 0}</p>
              </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 OC, factura, 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-[1100px]">
              <thead className="bg-slate-50">
                <tr>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Fecha OC</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">N° OC</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">N° factura</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-center text-xs font-semibold text-slate-600">Pago</th>
                  <th className="p-3 text-center text-xs font-semibold text-slate-600">Contabilidad</th>
                  <th className="p-3 text-center text-xs font-semibold text-slate-600">Inventario</th>
                  <th className="p-3 text-left text-xs font-semibold text-slate-600">Estado</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {trackingQuery.isLoading ? (
                  <tr>
                    <td className="p-4 text-center text-gray-600" colSpan={11}>
                      Cargando datos del libro OC…
                    </td>
                  </tr>
                ) : rows.length === 0 ? (
                  <tr>
                    <td className="p-4 text-center text-gray-600" colSpan={11}>
                      No hay órdenes de compra para los filtros seleccionados.
                    </td>
                  </tr>
                ) : (
                  rows.map((row) => (
                    <tr key={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 != null && row.document_type !== "" ? `(${row.document_type})` : ""}
                      </td>
                      <td className="p-3 text-sm whitespace-nowrap">
                        {row.invoice_folio
                          ? `${row.invoice_folio}${
                              row.invoice_document_type != null && row.invoice_document_type !== ""
                                ? ` (${row.invoice_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-center">
                        {showPaidOk(row.status) ? (
                          <Check className="w-5 h-5 text-green-600 mx-auto" aria-label="Pagado" />
                        ) : (
                          <span className="text-slate-300">—</span>
                        )}
                      </td>
                      <td className="p-3 text-center">
                        {showAccountedOk(row.status) ? (
                          <Check className="w-5 h-5 text-green-600 mx-auto" aria-label="Contabilizado" />
                        ) : (
                          <span className="text-slate-300">—</span>
                        )}
                      </td>
                      <td className="p-3 text-center">
                        {showInventoryOk(row.status) ? (
                          <Check className="w-5 h-5 text-green-600 mx-auto" aria-label="Inventariado" />
                        ) : (
                          <span className="text-slate-300">—</span>
                        )}
                      </td>
                      <td className="p-3 text-sm">{STATUS_LABELS[row.status] ?? row.status ?? "—"}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
