"use client";

import { useEffect, useState } from "react";

type Quote = { id: number; name: string; price: string; deliveryTime: number; company: string };

export type Address = {
  name: string;
  email: string;
  phone: string;
  cep: string;
  street: string;
  number: string;
  complement: string;
  neighborhood: string;
  city: string;
  state: string;
};

const emptyAddress: Address = {
  name: "",
  email: "",
  phone: "",
  cep: "",
  street: "",
  number: "",
  complement: "",
  neighborhood: "",
  city: "",
  state: "",
};

export function OrderForm({ productId, sizeId, price }: { productId: string; sizeId: string; price: number | null }) {
  const [address, setAddress] = useState<Address>(emptyAddress);
  const [quotes, setQuotes] = useState<Quote[] | null>(null);
  const [selectedQuote, setSelectedQuote] = useState<Quote | null>(null);
  const [calculating, setCalculating] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setQuotes(null);
    setSelectedQuote(null);
  }, [sizeId]);

  function update<K extends keyof Address>(key: K, value: string) {
    setAddress((a) => ({ ...a, [key]: value }));
    if (key === "cep") {
      setQuotes(null);
      setSelectedQuote(null);
    }
  }

  async function handleCalculate() {
    setCalculating(true);
    setError(null);
    setQuotes(null);
    setSelectedQuote(null);
    try {
      const res = await fetch("/api/frete", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ productId, sizeId, cep: address.cep }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? "Erro ao calcular frete");
      setQuotes(data.quotes);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erro ao calcular frete");
    } finally {
      setCalculating(false);
    }
  }

  const addressComplete =
    address.name && address.email && address.cep && address.street && address.number && address.neighborhood && address.city && address.state;
  const canBuy = price && addressComplete && selectedQuote;

  async function handleBuy() {
    if (!canBuy) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ productId, sizeId, address, shipping: selectedQuote }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? "Erro ao iniciar pagamento");
      window.location.href = data.initPoint;
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erro ao iniciar pagamento");
      setSubmitting(false);
    }
  }

  if (!price) {
    return (
      <button type="button" disabled className="mt-8 w-full rounded-full bg-zinc-300 px-6 py-3 text-sm font-medium text-zinc-500">
        Preço sob consulta
      </button>
    );
  }

  return (
    <div className="mt-6 space-y-5">
      <div>
        <h2 className="text-sm font-medium text-zinc-900">Dados para entrega</h2>
        <div className="mt-2 grid grid-cols-2 gap-2">
          <input className="col-span-2 rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="Nome completo" value={address.name} onChange={(e) => update("name", e.target.value)} />
          <input className="col-span-2 rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="E-mail" type="email" value={address.email} onChange={(e) => update("email", e.target.value)} />
          <input className="col-span-2 rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="Telefone/WhatsApp" value={address.phone} onChange={(e) => update("phone", e.target.value)} />
          <input className="rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="CEP" value={address.cep} onChange={(e) => update("cep", e.target.value)} />
          <input className="rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="Número" value={address.number} onChange={(e) => update("number", e.target.value)} />
          <input className="col-span-2 rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="Rua" value={address.street} onChange={(e) => update("street", e.target.value)} />
          <input className="col-span-2 rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="Complemento (opcional)" value={address.complement} onChange={(e) => update("complement", e.target.value)} />
          <input className="rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="Bairro" value={address.neighborhood} onChange={(e) => update("neighborhood", e.target.value)} />
          <input className="rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="Cidade" value={address.city} onChange={(e) => update("city", e.target.value)} />
          <input className="col-span-2 rounded border border-zinc-300 px-3 py-2 text-sm" placeholder="Estado (UF)" maxLength={2} value={address.state} onChange={(e) => update("state", e.target.value.toUpperCase())} />
        </div>
      </div>

      <div>
        <button
          type="button"
          onClick={handleCalculate}
          disabled={calculating || address.cep.length < 8}
          className="rounded border border-zinc-900 px-4 py-2 text-sm text-zinc-900 disabled:opacity-40"
        >
          {calculating ? "Calculando..." : "Calcular frete"}
        </button>

        {quotes && (
          <ul className="mt-3 divide-y divide-zinc-200 rounded border border-zinc-200 text-sm">
            {quotes.map((q) => (
              <li key={q.id} className="flex items-center gap-3 px-3 py-2">
                <input
                  type="radio"
                  name="shipping"
                  checked={selectedQuote?.id === q.id}
                  onChange={() => setSelectedQuote(q)}
                />
                <span className="flex-1">
                  {q.company} · {q.name}
                  <span className="ml-1 text-zinc-500">({q.deliveryTime} dias úteis)</span>
                </span>
                <span className="font-medium">
                  {Number(q.price).toLocaleString("pt-BR", { style: "currency", currency: "BRL" })}
                </span>
              </li>
            ))}
          </ul>
        )}
      </div>

      {error && <p className="text-sm text-red-600">{error}</p>}

      <button
        type="button"
        onClick={handleBuy}
        disabled={!canBuy || submitting}
        className="w-full rounded-full bg-zinc-900 px-6 py-3 text-sm font-medium text-white transition-colors hover:bg-zinc-700 disabled:opacity-40"
      >
        {submitting ? "Redirecionando..." : "Comprar"}
      </button>
    </div>
  );
}
