"use client";

import { useEffect, useState, useCallback, useMemo } from "react";
import Link from "next/link";
import { FileText, Plus, Search, Filter, Bell, BellOff } from "lucide-react";
import { motion } from "framer-motion";
import { listPedidos } from "@/lib/pb/pedidos";
import {
  type Pedido,
  type EstadoPedido,
  type EstadoCortes,
  ESTADO_PEDIDO_LABELS,
  ESTADO_CORTES_LABELS,
} from "@/lib/types/pedido";
import { money, dateShort } from "@/lib/format";
import { EstadoPedidoBadge, EstadoCortesBadge, PipelineBadge } from "@/components/pedidos/EstadoBadge";
import { inferEtapaProduccion, PIPELINE_ETAPAS, pedidoEntregaBgClass } from "@/lib/pedidos/pipeline";
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";

export default function PedidosListPage() {
  const [pedidos, setPedidos] = useState<Pedido[]>([]);
  const [loading, setLoading] = useState(true);
  const [estadoP, setEstadoP] = useState<EstadoPedido[]>(() => {
    if (typeof window !== "undefined") {
      const stored = localStorage.getItem("fibromuebles_filtro_estado_pedido");
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch (e) {
          return [];
        }
      }
    }
    return [];
  });
  const [estadoC, setEstadoC] = useState<EstadoCortes | "todos">("todos");
  const [search, setSearch] = useState("");
  const [sortField, setSortField] = useState<string>("creacion");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");

  const reload = useCallback(async () => {
    setLoading(true);
    try {
      const res = await listPedidos({ estados_pedido: estadoP, estado_cortes: estadoC, search, perPage: 500 });
      setPedidos(res.items);
    } finally {
      setLoading(false);
    }
  }, [estadoP, estadoC, search]);

  function toggleEstadoPedido(estado: EstadoPedido) {
    setEstadoP((prev) => prev.includes(estado) ? prev.filter((item) => item !== estado) : [...prev, estado]);
  }

  useEffect(() => {
    if (typeof window !== "undefined") {
      localStorage.setItem("fibromuebles_filtro_estado_pedido", JSON.stringify(estadoP));
    }
  }, [estadoP]);

  useEffect(() => {
    const t = setTimeout(reload, search ? 250 : 0);
    return () => clearTimeout(t);
  }, [reload, search]);

  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortOrder((prev) => (prev === "asc" ? "desc" : "asc"));
    } else {
      setSortField(field);
      setSortOrder("desc");
    }
  };

  const sortedPedidos = useMemo(() => {
    return [...pedidos].sort((a, b) => {
      let valA: any = "";
      let valB: any = "";

      switch (sortField) {
        case "numero":
          // Intentar ordenar por numero (que es entero) o codigo
          valA = a.numero || 0;
          valB = b.numero || 0;
          break;
        case "cliente":
          valA = (a.expand?.cliente?.nombre || "").toLowerCase();
          valB = (b.expand?.cliente?.nombre || "").toLowerCase();
          break;
        case "creacion":
          valA = new Date(a.fecha_creacion || 0).getTime();
          valB = new Date(b.fecha_creacion || 0).getTime();
          break;
        case "entrega":
          valA = new Date(a.fecha_entrega_estimada || 0).getTime();
          valB = new Date(b.fecha_entrega_estimada || 0).getTime();
          break;
        case "total":
          valA = a.total || 0;
          valB = b.total || 0;
          break;
        case "saldo":
          valA = a.saldo || 0;
          valB = b.saldo || 0;
          break;
        case "pipeline": {
          const stageA = a.etapa_produccion || inferEtapaProduccion(a);
          const stageB = b.etapa_produccion || inferEtapaProduccion(b);
          valA = PIPELINE_ETAPAS.indexOf(stageA);
          valB = PIPELINE_ETAPAS.indexOf(stageB);
          break;
        }
        default:
          valA = new Date(a.fecha_creacion || 0).getTime();
          valB = new Date(b.fecha_creacion || 0).getTime();
      }

      if (valA < valB) return sortOrder === "asc" ? -1 : 1;
      if (valA > valB) return sortOrder === "asc" ? 1 : -1;
      return 0;
    });
  }, [pedidos, sortField, sortOrder]);

  const renderSortIcon = (field: string) => {
    if (sortField !== field) return null;
    return sortOrder === "asc" ? " ▴" : " ▾";
  };

  return (
    <div className="max-w-7xl">
      <div className="flex items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-extrabold text-ink">Pedidos</h1>
          <p className="text-sm text-ink-soft mt-0.5">
            {pedidos.length} {pedidos.length === 1 ? "pedido" : "pedidos"}
          </p>
        </div>
        <div className="flex flex-wrap justify-end gap-2">
          <Link href="/presupuestos/nuevo">
            <Button size="lg" variant="secondary">
              <FileText size={18} /> Nuevo presupuesto
            </Button>
          </Link>
          <Link href="/pedidos/rapido">
            <Button size="lg">
              <Plus size={18} /> Pedido rápido
            </Button>
          </Link>
        </div>
      </div>

      {/* Filters */}
      <div className="card p-4 mb-4 flex flex-col gap-4">
        {/* Fila 1: Buscar y Estado de cortes */}
        <div className="flex flex-col md:flex-row gap-3 md:items-end">
          <div className="flex-1 min-w-0">
            <Input
              label="Buscar"
              placeholder="Nombre, celular, codigo o numero"
              prefix={<Search size={16} />}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          <FilterSelect
            label="Estado cortes"
            value={estadoC}
            onChange={(v) => setEstadoC(v as EstadoCortes | "todos")}
            options={[
              { v: "todos", l: "Todos" },
              ...Object.entries(ESTADO_CORTES_LABELS).map(([v, l]) => ({ v, l })),
            ]}
          />
        </div>

        {/* Fila 2: Estado de pedido (Checkboxes lineales) */}
        <div className="rounded-xl border border-line bg-surface p-3">
          <div className="mb-2 flex items-center justify-between gap-3">
            <span className="text-sm font-medium text-ink-soft">Estado de pedido</span>
            <button type="button" onClick={() => setEstadoP([])} className="text-xs font-semibold text-brand-dark">Limpiar filtros</button>
          </div>
          <div className="flex flex-wrap gap-2">
            {Object.entries(ESTADO_PEDIDO_LABELS).map(([value, label]) => (
              <label key={value} className="flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm text-ink-soft hover:bg-canvas cursor-pointer border border-line/50">
                <input
                  type="checkbox"
                  checked={estadoP.includes(value as EstadoPedido)}
                  onChange={() => toggleEstadoPedido(value as EstadoPedido)}
                  className="h-4 w-4 accent-brand"
                />
                {label}
              </label>
            ))}
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="card overflow-hidden">
        {loading ? (
          <div className="p-10 text-center text-faint text-sm">Cargando…</div>
        ) : pedidos.length === 0 ? (
          <EmptyState />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-line bg-canvas/50 text-left select-none">
                  <Th className="cursor-pointer hover:bg-canvas" onClick={() => handleSort("numero")}># {renderSortIcon("numero")}</Th>
                  <Th className="cursor-pointer hover:bg-canvas" onClick={() => handleSort("cliente")}>Cliente {renderSortIcon("cliente")}</Th>
                  <Th className="cursor-pointer hover:bg-canvas" onClick={() => handleSort("creacion")}>Creación {renderSortIcon("creacion")}</Th>
                  <Th className="cursor-pointer hover:bg-canvas" onClick={() => handleSort("entrega")}>Entrega {renderSortIcon("entrega")}</Th>
                  <Th className="cursor-pointer hover:bg-canvas text-right" onClick={() => handleSort("total")}>Total {renderSortIcon("total")}</Th>
                  <Th className="cursor-pointer hover:bg-canvas text-right" onClick={() => handleSort("saldo")}>Saldo {renderSortIcon("saldo")}</Th>
                  <Th className="cursor-pointer hover:bg-canvas" onClick={() => handleSort("pipeline")}>Pipeline {renderSortIcon("pipeline")}</Th>
                  <Th>Aviso</Th>
                </tr>
              </thead>
              <tbody>
                {sortedPedidos.map((p, i) => (
                  <motion.tr
                    key={p.id}
                    initial={{ opacity: 0, y: 4 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: i * 0.015 }}
                    className={`border-b border-line/60 last:border-b-0 hover:bg-canvas/50 cursor-pointer ${p.urgente ? "bg-red-50/70" : ""}`}
                    onClick={() => {
                      window.location.href = `/pedidos/${p.id}`;
                    }}
                  >
                    <Td>
                      <div className="font-bold text-ink">
                        {p.codigo || (p.numero ? `#${p.numero}` : "Borrador")}
                        {p.urgente && (
                          <span className="ml-1.5 rounded-full bg-red-600 px-1.5 py-0.5 align-middle text-[9px] font-extrabold text-white">URGENTE</span>
                        )}
                      </div>
                      {(p.hay_que_medir || p.hay_que_enviar || p.hay_que_instalar || p.requiere_pintura) && (
                        <div className="mt-1 flex flex-wrap gap-1">
                          {p.hay_que_medir && <span className="rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-bold text-amber-700">Medir</span>}
                          {p.hay_que_enviar && <span className="rounded-full bg-blue-100 px-1.5 py-0.5 text-[10px] font-bold text-blue-700">Enviar</span>}
                          {p.hay_que_instalar && <span className="rounded-full bg-red-100 px-1.5 py-0.5 text-[10px] font-bold text-red-700">Instalar</span>}
                          {p.requiere_pintura && <span className="rounded-full bg-purple-100 px-1.5 py-0.5 text-[10px] font-bold text-purple-700">Pintar</span>}
                        </div>
                      )}
                    </Td>
                    <Td>
                      <div className="font-medium text-ink">
                        {p.expand?.cliente?.nombre || "—"}
                      </div>
                      <div className="text-xs text-faint">
                        {p.expand?.cliente?.celular || ""}
                      </div>
                    </Td>
                    <Td className="text-ink-soft text-sm">{dateShort(p.fecha_creacion)}</Td>
                    <Td className="text-ink-soft text-sm">
                      {(() => {
                        const bg = pedidoEntregaBgClass(p);
                        const txt = dateShort(p.fecha_entrega_estimada) || "—";
                        return bg
                          ? <span className={`inline-block rounded-md px-2 py-0.5 font-semibold ${bg}`}>{txt}</span>
                          : <span>{txt}</span>;
                      })()}
                    </Td>
                    <Td className="text-right tabular-nums font-medium">{money(p.total)}</Td>
                    <Td
                      className={`text-right tabular-nums font-semibold ${
                        p.saldo > 0 ? "text-bad" : "text-good"
                      }`}
                    >
                      {money(p.saldo)}
                    </Td>
                    <Td>
                      <PipelineBadge value={p.etapa_produccion || inferEtapaProduccion(p)} size="sm" />
                    </Td>
                    <Td>
                      {p.avisado_retiro ? (
                        <Bell size={16} className="text-good" />
                      ) : (
                        <BellOff size={16} className="text-faint" />
                      )}
                    </Td>
                  </motion.tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

function Th({ children, className, onClick }: { children: React.ReactNode; className?: string; onClick?: () => void }) {
  return (
    <th
      onClick={onClick}
      className={`px-3 py-2.5 text-[11px] font-bold uppercase tracking-wider text-faint ${className || ""}`}
    >
      {children}
    </th>
  );
}

function Td({ children, className }: { children: React.ReactNode; className?: string }) {
  return <td className={`px-3 py-3 ${className || ""}`}>{children}</td>;
}

function FilterSelect({
  label,
  value,
  onChange,
  options,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  options: { v: string; l: string }[];
}) {
  return (
    <label className="flex flex-col gap-1.5">
      <span className="text-sm font-medium text-ink-soft">{label}</span>
      <div className="flex items-center gap-2 px-3 h-11 rounded-xl bg-surface border border-line focus-within:border-brand">
        <Filter size={16} className="text-faint" />
        <select
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="bg-transparent outline-none text-ink min-w-[140px]"
        >
          {options.map((o) => (
            <option key={o.v} value={o.v}>
              {o.l}
            </option>
          ))}
        </select>
      </div>
    </label>
  );
}

function EmptyState() {
  return (
    <div className="p-16 text-center">
      <p className="text-ink-soft mb-4">No hay pedidos cargados todavía.</p>
      <Link href="/pedidos/nuevo">
        <Button>
          <Plus size={16} /> Cargar el primero
        </Button>
      </Link>
    </div>
  );
}
