"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { Truck, Box, CheckCircle2, AlertCircle, Loader2, Settings, Store, Zap, Flame, X } from "lucide-react";
import { formatMoney } from "@/utils/formatters";

export type ShippingOption = {
  id: string;
  /* "pickup" nunca sai da cotacao daqui: ele chega junto com o pedido do
     catalogo, quando o cliente escolheu retirar no balcao da loja. */
  provider?: "melhor_envio" | "superfrete" | "pickup";
  provider_label?: string;
  name: string;
  service: string; // Sedex, PAC, Jadlog, etc.
  price: number;
  delivery_time: number; // dias
  logo_url?: string;
  pickup?: {
    location_id?: string;
    name?: string;
    address_summary?: string;
    instructions?: string;
  } | null;
};

type ShippingProviderResult = {
  provider: "melhor_envio" | "superfrete";
  provider_label: string;
  configured: boolean;
  options: ShippingOption[];
  error?: string;
};

const SHIPPING_PROVIDER_LOGOS: Record<string, string> = {
  melhor_envio: "https://logodownload.org/wp-content/uploads/2020/12/melhor-envio-logo.png",
  superfrete: "https://superfrete.com/favicon.ico",
};

interface ShippingCalculatorProps {
  initialZip?: string;
  selectedOption?: ShippingOption | null;
  onSelectShipping: (option: ShippingOption | null) => void;
  disabled?: boolean;
}

export function ShippingCalculator({ initialZip = "", selectedOption = null, onSelectShipping, disabled }: ShippingCalculatorProps) {
  const normalizedSelectedProvider = selectedOption?.provider || "melhor_envio";
  const selectedIsPickup = selectedOption?.provider === "pickup";
  const [zip, setZip] = useState(initialZip);
  const [weight, setWeight] = useState("1");
  const [width, setWidth] = useState("20");
  const [height, setHeight] = useState("20");
  const [length, setLength] = useState("20");
  const [loading, setLoading] = useState(false);
  const [providerResults, setProviderResults] = useState<ShippingProviderResult[] | null>(null);
  const [selectedId, setSelectedId] = useState<string | null>(
    selectedOption ? `${normalizedSelectedProvider}:${selectedOption.id}` : null
  );
  const [error, setError] = useState("");
  const [configured, setConfigured] = useState<boolean | null>(null);
  const [providerConfig, setProviderConfig] = useState<Record<string, boolean> | null>(null);
  const [destinationAddress, setDestinationAddress] = useState<string | null>(null);

  const getErrorMessage = (err: unknown) => {
    if (err instanceof Error) return err.message;
    if (typeof err === "string") return err;
    return "Ocorreu um erro ao calcular o frete.";
  };

  useEffect(() => {
    async function checkStatus() {
      try {
        const res = await fetch("/api/shipping/status");
        if (res.ok) {
          const data = await res.json();
          setConfigured(data.configured);
          setProviderConfig(data.providers || null);
        } else {
          setConfigured(false);
          setProviderConfig(null);
        }
      } catch {
        setConfigured(false);
        setProviderConfig(null);
      }
    }
    checkStatus();
  }, []);

  const handleCalculate = async () => {
    if (!zip || zip.length < 8) {
      setError("Informe um CEP válido.");
      return;
    }
    setError("");
    setLoading(true);
    setProviderResults(null);
    setSelectedId(null);
    setDestinationAddress(null);

    try {
      // Busca endereço via CEP
      fetch(`https://viacep.com.br/ws/${zip.replace(/\D/g, "")}/json/`)
        .then((res) => res.json())
        .then((data) => {
          if (!data.erro) {
            setDestinationAddress(`${data.logradouro}, ${data.bairro}, ${data.localidade} - ${data.uf}`);
          }
        })
        .catch(() => {
          // Ignora erro de CEP na UI se falhar, foca no cálculo
        });

      const res = await fetch("/api/shipping/calculate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          zip,
          weight,
          width,
          height,
          length,
        }),
      });

      const data = await res.json();
      const rawProviders = Array.isArray(data?.providers)
        ? (data.providers as ShippingProviderResult[])
        : [];

      if (!res.ok && rawProviders.length === 0) {
        throw new Error(data.error || "Erro ao calcular frete.");
      }

      if (rawProviders.length === 0) {
        if (Array.isArray(data)) {
          const fallbackOptions = data as ShippingOption[];
          if (fallbackOptions.length > 0) {
            setProviderResults([
              {
                provider: "melhor_envio",
                provider_label: "Melhor Envio",
                configured: true,
                options: fallbackOptions.map((option) => ({
                  provider: option.provider || "melhor_envio",
                  provider_label: option.provider_label || "Melhor Envio",
                  ...option,
                })),
              },
            ]);
            return;
          }
        }
        setError("Nenhuma opção de frete encontrada para este CEP/Dimensões.");
        return;
      }

      const normalizedProviders = rawProviders.map((provider) => ({
        ...provider,
        options: (Array.isArray(provider.options) ? provider.options : []).map((option) => ({
          ...option,
          provider: option.provider || provider.provider,
          provider_label: option.provider_label || provider.provider_label,
        })),
      }));
      setProviderResults(normalizedProviders);

      const hasAnyOption = normalizedProviders.some((provider) => provider.options.length > 0);
      if (!hasAnyOption) {
         setError(data?.error || "Nenhuma opção de frete encontrada para este CEP/Dimensões.");
         return;
      }
    } catch (err: unknown) {
      setError(getErrorMessage(err));
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handleSelect = (option: ShippingOption) => {
    const optionId = `${option.provider}:${option.id}`;
    if (selectedId === optionId) {
      setSelectedId(null);
      onSelectShipping(null);
    } else {
      setSelectedId(optionId);
      onSelectShipping(option);
    }
  };

  const handleDelete = () => {
    setSelectedId(null);
    onSelectShipping(null);
  };

  if (configured === null) {
    return (
      <div className="bg-white rounded-3xl border border-[var(--ks-color-border-subtle)] p-6 shadow-sm flex items-center justify-center h-48">
        <Loader2 className="animate-spin text-zinc-400" size={24} />
      </div>
    );
  }

  if (configured === false) {
    return (
      <div className="bg-white rounded-3xl border border-[var(--ks-color-border-subtle)] p-8 shadow-sm text-center">
        <div className="mx-auto w-12 h-12 rounded-full bg-zinc-100 flex items-center justify-center text-zinc-400 mb-4">
          <Truck size={24} />
        </div>
        <h3 className="text-lg font-bold text-zinc-900">Gateways de Frete</h3>
        <p className="text-sm text-zinc-500 max-w-sm mx-auto mt-2 mb-6">
          Conecte um gateway de frete para calcular prazos e preços de entrega automaticamente nos seus orçamentos.
        </p>
        <Link
          href="/dashboard/settings/shipping"
          className="inline-flex items-center gap-2 px-5 py-2.5 bg-[var(--ks-color-primary)] text-white rounded-xl hover:bg-[var(--ks-color-primary-strong)] transition-colors text-sm font-medium"
        >
          <Settings size={16} />
          Configurar Integrações
        </Link>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-3xl border border-[var(--ks-color-border-subtle)] p-6 shadow-sm">
      <div className="flex items-center gap-3 mb-6">
        <div className="w-10 h-10 rounded-full bg-blue-50 flex items-center justify-center text-blue-600">
          <Truck size={20} />
        </div>
        <div>
          <h3 className="text-lg font-bold text-zinc-900">Cotação de Frete</h3>
          <p className="text-sm text-zinc-500">Simule opções de entrega em tempo real.</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-12 gap-4 items-end bg-zinc-50/50 p-4 rounded-2xl border border-zinc-100">
        <div className="md:col-span-3 space-y-1.5">
          <label className="text-xs font-semibold text-zinc-500 uppercase tracking-wider">CEP Destino</label>
          <input
            value={zip}
            onChange={(e) => setZip(e.target.value.replace(/\D/g, "").slice(0, 8))}
            placeholder="00000-000"
            className="w-full px-3 py-2 rounded-xl border border-zinc-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 bg-white transition-all text-sm font-medium"
            disabled={disabled || loading}
          />
        </div>

        <div className="md:col-span-2 space-y-1.5">
          <label className="text-xs font-semibold text-zinc-500 uppercase tracking-wider flex items-center gap-1">
            Peso <span className="text-[10px] text-zinc-400 normal-case">(kg)</span>
          </label>
          <input
            value={weight}
            onChange={(e) => setWeight(e.target.value)}
            placeholder="1"
            className="w-full px-3 py-2 rounded-xl border border-zinc-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 bg-white transition-all text-sm font-medium"
            disabled={disabled || loading}
          />
        </div>

        <div className="md:col-span-5 grid grid-cols-3 gap-2">
          <div className="space-y-1.5">
            <label className="text-xs font-semibold text-zinc-500 uppercase tracking-wider flex items-center gap-1">
              Alt <span className="text-[10px] text-zinc-400 normal-case">(cm)</span>
            </label>
            <input
              value={height}
              onChange={(e) => setHeight(e.target.value)}
              placeholder="20"
              className="w-full px-3 py-2 rounded-xl border border-zinc-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 bg-white transition-all text-sm font-medium"
              disabled={disabled || loading}
            />
          </div>
          <div className="space-y-1.5">
            <label className="text-xs font-semibold text-zinc-500 uppercase tracking-wider flex items-center gap-1">
              Larg <span className="text-[10px] text-zinc-400 normal-case">(cm)</span>
            </label>
            <input
              value={width}
              onChange={(e) => setWidth(e.target.value)}
              placeholder="20"
              className="w-full px-3 py-2 rounded-xl border border-zinc-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 bg-white transition-all text-sm font-medium"
              disabled={disabled || loading}
            />
          </div>
          <div className="space-y-1.5">
            <label className="text-xs font-semibold text-zinc-500 uppercase tracking-wider flex items-center gap-1">
              Comp <span className="text-[10px] text-zinc-400 normal-case">(cm)</span>
            </label>
            <input
              value={length}
              onChange={(e) => setLength(e.target.value)}
              placeholder="20"
              className="w-full px-3 py-2 rounded-xl border border-zinc-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 bg-white transition-all text-sm font-medium"
              disabled={disabled || loading}
            />
          </div>
        </div>

        <div className="md:col-span-2">
          <button
            type="button"
            onClick={handleCalculate}
            disabled={disabled || loading}
            className="w-full h-[38px] bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-sm font-semibold transition-all active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 shadow-sm shadow-blue-600/20"
          >
            {loading ? <Loader2 size={16} className="animate-spin" /> : <Box size={16} />}
            Cotar
          </button>
        </div>
      </div>

      {error && (
        <div className="mt-4 flex items-center gap-2 text-red-600 text-sm bg-red-50 p-3 rounded-xl border border-red-100">
          <AlertCircle size={16} />
          {error}
        </div>
      )}

      {destinationAddress && (
        <div className="mt-3 px-4 py-2 bg-blue-50/50 rounded-xl text-xs text-blue-700 border border-blue-100 flex items-center gap-2">
          <div className="w-1.5 h-1.5 rounded-full bg-blue-500" />
          {destinationAddress}
        </div>
      )}

      {providerConfig && (providerConfig.melhor_envio === false || providerConfig.superfrete === false) ? (
        <div className="mt-3 px-4 py-2 bg-amber-50 rounded-xl text-xs text-amber-700 border border-amber-100">
          Uma das integrações de frete não está configurada. Você ainda pode cotar com a integração ativa.
        </div>
      ) : null}

      {!providerResults && selectedOption && (
        <div className="mt-6 animate-in fade-in slide-in-from-top-4 duration-500">
          <div className="text-xs font-semibold text-zinc-400 uppercase tracking-wider px-1 mb-3">
            {selectedIsPickup ? "Retirada no balcão" : "Frete Selecionado"}
          </div>
          <div className="bg-blue-50/50 border border-blue-500 rounded-2xl p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 shadow-sm relative overflow-hidden group">
            <div className="absolute top-0 right-0 flex">
               <button 
                  onClick={handleDelete}
                  className="p-2 text-zinc-400 hover:text-red-600 hover:bg-red-50 transition-colors z-20"
                  title="Remover frete"
                >
                  <X size={16} />
                </button>
                <div className="p-2 text-blue-600 bg-white rounded-bl-2xl border-b border-l border-blue-100 shadow-sm">
                  <CheckCircle2 size={16} />
                </div>
            </div>

            <div className="flex items-center gap-4 w-full sm:w-auto">
              <div className="w-12 h-12 shrink-0 rounded-xl bg-white flex items-center justify-center p-2 border border-blue-100">
                {selectedIsPickup ? (
                  <Store className="text-blue-400" />
                ) : selectedOption.logo_url ? (
                  <Image
                    src={selectedOption.logo_url}
                    width={48}
                    height={48}
                    className="object-contain w-full h-full"
                    alt=""
                    unoptimized
                  />
                ) : (
                  <Box className="text-blue-300" />
                )}
              </div>
              <div>
                <div className="font-bold text-zinc-900 flex flex-wrap items-center gap-2">
                  {selectedOption.service}
                  <span className="text-[10px] font-medium px-1.5 py-0.5 rounded-md bg-white text-zinc-500 border border-blue-100">
                    {selectedOption.name}
                  </span>
                  <span className="text-[10px] font-medium px-1.5 py-0.5 rounded-md bg-blue-100 text-blue-700 border border-blue-200">
                    {selectedOption.provider_label || "Frete"}
                  </span>
                </div>
                <div className="text-xs text-zinc-500 mt-0.5">
                  {selectedIsPickup ? (
                    selectedOption.delivery_time > 0 ? (
                      <>
                        Pronto para retirar em{" "}
                        <span className="font-semibold text-zinc-700">{selectedOption.delivery_time} dias</span>
                      </>
                    ) : (
                      <span className="font-semibold text-zinc-700">Cliente retira na loja</span>
                    )
                  ) : (
                    <>
                      Chega em <span className="font-semibold text-zinc-700">{selectedOption.delivery_time} dias</span>
                    </>
                  )}
                </div>
              </div>
            </div>
            <div className="text-right w-full sm:w-auto">
              <div className="text-lg font-bold text-blue-600">
                {selectedIsPickup && selectedOption.price <= 0 ? "Grátis" : formatMoney(selectedOption.price)}
              </div>
            </div>
          </div>
        </div>
      )}

      {providerResults && (
        <div className="mt-6 space-y-3 animate-in fade-in slide-in-from-top-4 duration-500">
          <div className="text-xs font-semibold text-zinc-400 uppercase tracking-wider px-1">
            Opções Disponíveis
          </div>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 pt-3">
            {providerResults.map((provider) => {
              const options = Array.isArray(provider.options) ? provider.options : [];
              const cheapestPrice = options.length ? Math.min(...options.map((o) => o.price)) : 0;
              const fastestTime = options.length ? Math.min(...options.map((o) => o.delivery_time)) : 0;
              const isSuperFrete = provider.provider === "superfrete";
              const logoSize = isSuperFrete ? 44 : 120;
              const logoClass = isSuperFrete ? "h-11 w-11 object-contain shrink-0" : "h-7 w-auto object-contain shrink-0";

              return (
                <div key={provider.provider} className="rounded-2xl border border-zinc-200 p-3 space-y-3 bg-zinc-50/40">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2 min-w-0">
                      <Image
                        src={SHIPPING_PROVIDER_LOGOS[provider.provider] || SHIPPING_PROVIDER_LOGOS.superfrete}
                        alt={provider.provider_label}
                        width={logoSize}
                        height={logoSize}
                        className={logoClass}
                        unoptimized
                      />
                    </div>
                    <div className="text-xs text-zinc-500">{options.length} opção(ões)</div>
                  </div>
                  {provider.error ? (
                    <div className="text-xs text-amber-700 bg-amber-50 border border-amber-100 rounded-xl p-2">
                      {provider.error}
                    </div>
                  ) : null}
                  {options.length === 0 ? (
                    <div className="text-xs text-zinc-500 border border-dashed border-zinc-200 rounded-xl p-3 bg-white">
                      Nenhuma opção disponível para os dados informados.
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {options.map((opt) => {
                        const optionKey = `${opt.provider}:${opt.id}`;
                        const isSelected = selectedId === optionKey;
                        const isCheapest = opt.price === cheapestPrice;
                        const isFastest = opt.delivery_time === fastestTime;

                        return (
                          <button
                            key={optionKey}
                            type="button"
                            onClick={() => handleSelect(opt)}
                            className={`
                              relative group flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 rounded-2xl border text-left transition-all duration-200 gap-4 w-full
                              ${
                                isSelected
                                  ? "bg-blue-50/50 border-blue-500 shadow-md shadow-blue-500/10 ring-1 ring-blue-500"
                                  : "bg-white border-zinc-200 hover:border-blue-300 hover:bg-blue-50/30 hover:shadow-sm"
                              }
                            `}
                          >
                            {isFastest && (
                              <div className="absolute -top-3 left-4 px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 text-[10px] font-bold uppercase tracking-wider border border-amber-200 shadow-sm flex items-center gap-1 z-10">
                                <Zap size={10} className="fill-current" />
                                Mais Rápido
                              </div>
                            )}
                            {isCheapest && (
                              <div className={`absolute -top-3 ${isFastest ? "left-28" : "left-4"} px-2 py-0.5 rounded-full bg-rose-100 text-rose-700 text-[10px] font-bold uppercase tracking-wider border border-rose-200 shadow-sm flex items-center gap-1 z-10`}>
                                <Flame size={10} className="fill-current" />
                                Mais Barato
                              </div>
                            )}

                            <div className="flex items-center gap-4 w-full min-w-0 flex-1">
                              <div
                                className={`
                                  w-12 h-12 shrink-0 rounded-xl flex items-center justify-center p-2 transition-colors overflow-hidden
                                  ${isSelected ? "bg-white" : "bg-zinc-50 group-hover:bg-white"}
                                `}
                              >
                                {opt.logo_url ? (
                                  <Image
                                    src={opt.logo_url}
                                    alt={opt.name}
                                    width={48}
                                    height={48}
                                    className="object-contain w-full h-full"
                                    unoptimized
                                  />
                                ) : (
                                  <Box className="text-zinc-400" size={24} />
                                )}
                              </div>
                              <div className="min-w-0 flex-1">
                                <div className="font-bold text-zinc-900 flex flex-wrap items-center gap-2">
                                  <span className="truncate">{opt.service}</span>
                                  <span className="text-[10px] font-medium px-1.5 py-0.5 rounded-md bg-zinc-100 text-zinc-500 border border-zinc-200 whitespace-nowrap">
                                    {opt.name}
                                  </span>
                                </div>
                                <div className="text-xs text-zinc-500 mt-0.5 flex items-center gap-1">
                                  Chega em <span className="font-semibold text-zinc-700">{opt.delivery_time} dias</span>
                                </div>
                              </div>
                            </div>

                            <div className="text-right w-full sm:w-auto sm:min-w-[96px] shrink-0 flex flex-row sm:flex-col justify-between items-center sm:items-end gap-2 sm:gap-0 mt-2 sm:mt-0 pt-2 sm:pt-0 border-t sm:border-0 border-zinc-100">
                              <div className="text-xs text-zinc-400 sm:hidden">Valor do frete</div>
                              <div className="text-base sm:text-lg font-bold text-blue-600 whitespace-nowrap">{formatMoney(opt.price)}</div>
                              {isSelected && (
                                <div className="absolute top-0 right-0 -mt-2 -mr-2 bg-blue-600 text-white rounded-full p-1 shadow-sm animate-in zoom-in duration-300 z-10">
                                  <CheckCircle2 size={14} />
                                </div>
                              )}
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
