"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import ImageUpload from "@/components/image-upload";
import { ArrowLeft, ExternalLink, Save } from "lucide-react";

type SponsoredSupplier = {
  id: string;
  name: string;
  legal_name: string | null;
  cnpj: string;
  category: string | null;
  city: string | null;
  email: string;
  phone: string;
  payment_terms_primary: string;
  payment_terms_secondary: string;
  subscriber_discount: string | null;
  image_url: string | null;
  description: string | null;
  website_url: string | null;
  notes: string | null;
  active: boolean;
  position: number;
};

const PAYMENT_PRIMARY_OPTIONS = ["À vista", "14 dias", "15 dias", "28 dias", "30 dias", "30/60 dias", "15/30 dias", "15/30/45 dias", "60 dias"];
const PAYMENT_SECONDARY_OPTIONS = ["Boleto", "PIX", "Boleto/PIX", "PIX / boleto", "Cartão"];

function digits(value: string) {
  return String(value || "").replace(/\D/g, "");
}

function formatPhone(value: string) {
  const d = digits(value).slice(0, 11);
  if (d.length <= 2) return d ? `(${d}` : "";
  if (d.length <= 6) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
  if (d.length <= 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
  return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
}

function formatCnpj(value: string) {
  const d = digits(value).slice(0, 14);
  if (d.length <= 2) return d;
  if (d.length <= 5) return `${d.slice(0, 2)}.${d.slice(2)}`;
  if (d.length <= 8) return `${d.slice(0, 2)}.${d.slice(2, 5)}.${d.slice(5)}`;
  if (d.length <= 12) return `${d.slice(0, 2)}.${d.slice(2, 5)}.${d.slice(5, 8)}/${d.slice(8)}`;
  return `${d.slice(0, 2)}.${d.slice(2, 5)}.${d.slice(5, 8)}/${d.slice(8, 12)}-${d.slice(12)}`;
}

export default function SponsoredSupplierFormClient({
  mode,
  initial,
}: {
  mode: "create" | "edit";
  initial: SponsoredSupplier | null;
}) {
  const router = useRouter();
  const formRef = useRef<HTMLDivElement | null>(null);
  const base = useMemo<SponsoredSupplier>(
    () =>
      initial || {
        id: "",
        name: "",
        legal_name: "",
        cnpj: "",
        category: "",
        city: "São Paulo",
        email: "",
        phone: "",
        payment_terms_primary: "30 dias",
        payment_terms_secondary: "Boleto",
        subscriber_discount: "",
        image_url: "",
        description: "",
        website_url: "",
        notes: "",
        active: true,
        position: 0,
      },
    [initial]
  );

  const [draft, setDraft] = useState<SponsoredSupplier>(base);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  useEffect(() => {
    setDraft(base);
    setMessage(null);
  }, [base]);

  function readField(name: string, fallback = "") {
    const element = formRef.current?.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`);
    return typeof element?.value === "string" ? element.value : fallback;
  }

  function getCurrentDraft() {
    return {
      ...draft,
      name: readField("name", draft.name),
      legal_name: readField("legal_name", draft.legal_name || "") || null,
      cnpj: digits(readField("cnpj", draft.cnpj)),
      category: readField("category", draft.category || "") || null,
      city: readField("city", draft.city || "") || null,
      email: readField("email", draft.email),
      phone: digits(readField("phone", draft.phone)),
      payment_terms_primary: readField("payment_terms_primary", draft.payment_terms_primary),
      payment_terms_secondary: readField("payment_terms_secondary", draft.payment_terms_secondary),
      subscriber_discount: readField("subscriber_discount", draft.subscriber_discount || "") || null,
      image_url: draft.image_url || null,
      description: readField("description", draft.description || "") || null,
      website_url: readField("website_url", draft.website_url || "") || null,
      notes: readField("notes", draft.notes || "") || null,
      active: readField("active_status", draft.active ? "ativo" : "inativo") === "ativo",
      position: Number(readField("position", String(draft.position || 0)) || 0),
    } satisfies SponsoredSupplier;
  }

  return (
    <div className="min-h-screen bg-slate-50/50 p-6 font-sans sm:p-8">
      <div className="mx-auto flex max-w-[1500px] flex-col gap-6">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
          <div className="space-y-1">
            <div className="flex items-center gap-3">
              <Link
                href="/fornecedores-patrocinados"
                className="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-white shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50"
                aria-label="Voltar"
                title="Voltar"
              >
                <ArrowLeft className="h-4.5 w-4.5 text-slate-700" />
              </Link>
              <div>
                <h1 className="text-2xl font-bold tracking-tight text-slate-900">
                  {mode === "create" ? "Novo fornecedor patrocinado" : "Editar fornecedor patrocinado"}
                </h1>
                <p className="text-slate-500">Esse cadastro alimenta a aba de patrocinados do Admin para todos os clientes.</p>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Link
              href="/fornecedores-patrocinados"
              className="inline-flex h-11 items-center justify-center rounded-xl bg-white px-4 text-sm font-semibold text-slate-700 shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50"
            >
              Cancelar
            </Link>
            <button
              type="button"
              disabled={saving}
              onClick={async () => {
                const currentDraft = getCurrentDraft();
                setDraft(currentDraft);
                const canSave =
                  Boolean(currentDraft.name.trim()) &&
                  digits(currentDraft.cnpj).length === 14 &&
                  Boolean(currentDraft.email.trim()) &&
                  digits(currentDraft.phone).length >= 10;
                if (!canSave) {
                  setMessage({
                    type: "error",
                    text: "Preencha nome, CNPJ valido, e-mail e telefone para salvar.",
                  });
                  return;
                }
                setSaving(true);
                setMessage(null);
                try {
                  const method = mode === "edit" ? "PATCH" : "POST";
                  const res = await fetch("/api/sponsored-suppliers", {
                    method,
                    headers: { "content-type": "application/json" },
                    body: JSON.stringify({
                      id: initial?.id,
                      name: currentDraft.name.trim(),
                      legal_name: currentDraft.legal_name?.trim() || null,
                      cnpj: digits(currentDraft.cnpj),
                      category: currentDraft.category?.trim() || null,
                      city: currentDraft.city?.trim() || null,
                      email: currentDraft.email.trim(),
                      phone: digits(currentDraft.phone),
                      payment_terms_primary: currentDraft.payment_terms_primary.trim() || "30 dias",
                      payment_terms_secondary: currentDraft.payment_terms_secondary.trim() || "Boleto",
                      subscriber_discount: currentDraft.subscriber_discount?.trim() || null,
                      image_url: currentDraft.image_url?.trim() || null,
                      description: currentDraft.description?.trim() || null,
                      website_url: currentDraft.website_url?.trim() || null,
                      notes: currentDraft.notes?.trim() || null,
                      active: currentDraft.active,
                      position: Number(currentDraft.position || 0),
                    }),
                  });
                  const json = (await res.json().catch(() => null)) as { error?: string } | null;
                  if (!res.ok) {
                    setMessage({ type: "error", text: json?.error || "Não foi possível salvar." });
                    return;
                  }
                  setMessage({ type: "success", text: "Fornecedor patrocinado salvo com sucesso." });
                  window.setTimeout(() => router.push("/fornecedores-patrocinados"), 220);
                } catch (error) {
                  setMessage({
                    type: "error",
                    text: error instanceof Error ? error.message : "Não foi possível salvar o fornecedor patrocinado.",
                  });
                } finally {
                  setSaving(false);
                }
              }}
              className="inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-slate-900 px-5 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800 disabled:opacity-60"
            >
              <Save className="h-4.5 w-4.5" />
              {saving ? "Salvando..." : "Salvar"}
            </button>
          </div>
        </div>

        <div ref={formRef} className="grid gap-6 lg:grid-cols-[1.1fr_0.9fr]">
          <div className="space-y-4">
            <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
              <div className="text-sm font-semibold text-slate-900">Dados principais</div>
              <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 p-4">
                <div className="text-sm font-semibold text-slate-900">Foto do fornecedor</div>
                <div className="mt-3">
                  <ImageUpload
                    bucket="products"
                    folder="owner/sponsored-suppliers"
                    value={draft.image_url || ""}
                    onChange={(url) => setDraft((prev) => ({ ...prev, image_url: url }))}
                    aspect={1}
                    ratioLabel="1:1"
                    hint="Recomendado: imagem quadrada com boa nitidez. Essa foto aparece na listagem e no modal do Admin."
                    disabled={saving}
                  />
                </div>
              </div>
              <div className="mt-4 grid gap-4 md:grid-cols-2">
                <label className="space-y-2 md:col-span-2">
                  <div className="text-sm font-semibold text-slate-900">Nome comercial</div>
                  <input
                    name="name"
                    value={draft.name}
                    onChange={(e) => setDraft((prev) => ({ ...prev, name: e.target.value }))}
                    placeholder="Ex: IRWIN Ferramentas"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2 md:col-span-2">
                  <div className="text-sm font-semibold text-slate-900">Razão social</div>
                  <input
                    name="legal_name"
                    value={draft.legal_name || ""}
                    onChange={(e) => setDraft((prev) => ({ ...prev, legal_name: e.target.value }))}
                    placeholder="Opcional"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">CNPJ</div>
                  <input
                    name="cnpj"
                    value={formatCnpj(draft.cnpj)}
                    onChange={(e) => setDraft((prev) => ({ ...prev, cnpj: digits(e.target.value) }))}
                    placeholder="00.000.000/0000-00"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Categoria</div>
                  <input
                    name="category"
                    value={draft.category || ""}
                    onChange={(e) => setDraft((prev) => ({ ...prev, category: e.target.value }))}
                    placeholder="Ex: Ferragens"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Cidade</div>
                  <input
                    name="city"
                    value={draft.city || ""}
                    onChange={(e) => setDraft((prev) => ({ ...prev, city: e.target.value }))}
                    placeholder="Cidade"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Posição</div>
                  <input
                    name="position"
                    value={String(draft.position ?? 0)}
                    onChange={(e) => setDraft((prev) => ({ ...prev, position: Number(e.target.value || 0) }))}
                    inputMode="numeric"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>
              </div>
            </div>

            <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
              <div className="text-sm font-semibold text-slate-900">Contato e condições</div>
              <div className="mt-4 grid gap-4 md:grid-cols-2">
                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">E-mail</div>
                  <input
                    name="email"
                    value={draft.email}
                    onChange={(e) => setDraft((prev) => ({ ...prev, email: e.target.value }))}
                    placeholder="contato@empresa.com.br"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Telefone</div>
                  <input
                    name="phone"
                    value={formatPhone(draft.phone)}
                    onChange={(e) => setDraft((prev) => ({ ...prev, phone: digits(e.target.value) }))}
                    placeholder="(11) 99999-9999"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Condição principal</div>
                  <select
                    name="payment_terms_primary"
                    value={draft.payment_terms_primary}
                    onChange={(e) => setDraft((prev) => ({ ...prev, payment_terms_primary: e.target.value }))}
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-700 outline-none"
                  >
                    {PAYMENT_PRIMARY_OPTIONS.map((item) => (
                      <option key={item} value={item}>
                        {item}
                      </option>
                    ))}
                  </select>
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Forma de pagamento</div>
                  <select
                    name="payment_terms_secondary"
                    value={draft.payment_terms_secondary}
                    onChange={(e) => setDraft((prev) => ({ ...prev, payment_terms_secondary: e.target.value }))}
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-700 outline-none"
                  >
                    {PAYMENT_SECONDARY_OPTIONS.map((item) => (
                      <option key={item} value={item}>
                        {item}
                      </option>
                    ))}
                  </select>
                </label>

                <label className="space-y-2 md:col-span-2">
                  <div className="text-sm font-semibold text-slate-900">Oferta para assinantes Ktalogu</div>
                  <input
                    name="subscriber_discount"
                    value={draft.subscriber_discount || ""}
                    onChange={(e) => setDraft((prev) => ({ ...prev, subscriber_discount: e.target.value }))}
                    placeholder="Ex: 10% OFF, 5% no PIX ou frete gratis"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2 md:col-span-2">
                  <div className="text-sm font-semibold text-slate-900">Descrição do fornecedor</div>
                  <textarea
                    name="description"
                    value={draft.description || ""}
                    onChange={(e) => setDraft((prev) => ({ ...prev, description: e.target.value }))}
                    rows={4}
                    className="w-full resize-none rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm text-slate-800 outline-none"
                    placeholder="Explique o que esse fornecedor faz, com o que trabalha, diferenciais e principais linhas de atuação."
                  />
                </label>

                <label className="space-y-2 md:col-span-2">
                  <div className="text-sm font-semibold text-slate-900">Site</div>
                  <input
                    name="website_url"
                    value={draft.website_url || ""}
                    onChange={(e) => setDraft((prev) => ({ ...prev, website_url: e.target.value }))}
                    placeholder="https://..."
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2 md:col-span-2">
                  <div className="text-sm font-semibold text-slate-900">Observações</div>
                  <textarea
                    name="notes"
                    value={draft.notes || ""}
                    onChange={(e) => setDraft((prev) => ({ ...prev, notes: e.target.value }))}
                    rows={4}
                    className="w-full resize-none rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm text-slate-800 outline-none"
                    placeholder="Observações comerciais, diferenciais, regras, etc."
                  />
                </label>
              </div>
            </div>

            {message ? (
              <div
                className={[
                  "rounded-2xl border px-4 py-3 text-sm font-semibold",
                  message.type === "success" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-rose-200 bg-rose-50 text-rose-700",
                ].join(" ")}
              >
                {message.text}
              </div>
            ) : null}
          </div>

          <div className="space-y-4">
            <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
              <div className="text-sm font-semibold text-slate-900">Exibição</div>
              <div className="mt-4 grid gap-4">
                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Status</div>
                  <select
                    name="active_status"
                    value={draft.active ? "ativo" : "inativo"}
                    onChange={(e) => setDraft((prev) => ({ ...prev, active: e.target.value === "ativo" }))}
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-700 outline-none"
                  >
                    <option value="ativo">Ativo</option>
                    <option value="inativo">Inativo</option>
                  </select>
                </label>

                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-600">
                  Ativos aparecem para todas as empresas na aba de patrocinados. Inativos ficam salvos apenas para gestão interna do Owner.
                </div>

                {draft.website_url ? (
                  <a
                    href={draft.website_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-white px-4 text-sm font-semibold text-slate-700 shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50"
                  >
                    <ExternalLink className="h-4.5 w-4.5 text-slate-400" />
                    Abrir site
                  </a>
                ) : null}
              </div>
            </div>

            <div className="rounded-2xl border border-slate-200 bg-[linear-gradient(135deg,rgba(79,70,229,0.10)_0%,rgba(124,58,237,0.10)_100%)] p-5 shadow-sm">
              <div className="text-sm font-semibold text-slate-900">Como aparece no Admin</div>
              <div className="mt-3 space-y-2 text-sm text-slate-600">
                <div>Foto, nome comercial, CNPJ, categoria e cidade.</div>
                <div>Contato principal e condições de pagamento.</div>
                <div>Oferta destacada para assinantes Ktalogu, quando preenchida.</div>
                <div>Descrição institucional no modal do fornecedor.</div>
                <div>Link do site e observações comerciais, quando preenchidos.</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
