import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Building2, UserPlus, Mail, Lock, Sparkles, Check, Wand2, ChevronRight } from "lucide-react";
import { api } from "../../lib/api";
import { Modal } from "../Modal";
import { Spinner } from "../ui";
import { cn } from "../../lib/format";

interface Props {
  open: boolean;
  onClose: () => void;
  onCreated?: () => void;
}

const PLAN_OPTIONS = [
  { value: "trial", label: "Prueba", desc: "14 días" },
  { value: "pro", label: "Pro", desc: "Suscripción activa" },
  { value: "free", label: "Free", desc: "Plan gratuito" },
];

export function CreateBusinessModal({ open, onClose, onCreated }: Props) {
  const navigate = useNavigate();
  const { data: tplData } = useQuery({ queryKey: ["admin", "templates"], queryFn: () => api.admin.templates(), enabled: open });
  const templates = tplData?.templates ?? [];

  const [step, setStep] = useState<1 | 2>(1);
  const [template, setTemplate] = useState("estetica-spa");
  const [name, setName] = useState("");
  const [industry, setIndustry] = useState("");
  const [ownerName, setOwnerName] = useState("");
  const [ownerEmail, setOwnerEmail] = useState("");
  const [ownerPassword, setOwnerPassword] = useState("demo1234");
  const [plan, setPlan] = useState("trial");
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setStep(1);
    setError(null);
    setName("");
    setIndustry("");
    setOwnerName("");
    setOwnerEmail("");
    setOwnerPassword("demo1234");
    setPlan("trial");
    setTemplate("estetica-spa");
  }, [open]);

  // Auto-fill name/industry from selected template
  useEffect(() => {
    if (!open) return;
    const t = templates.find((x) => x.key === template);
    if (t && !name) setName(t.name === "Nuevo Negocio" ? "" : t.name);
    if (t && !industry) setIndustry(t.industry);
  }, [template, templates, open]); // eslint-disable-line react-hooks/exhaustive-deps

  const mut = useMutation({
    mutationFn: () =>
      api.admin.createBusiness({
        name,
        industry: industry || undefined,
        template,
        ownerName: ownerName || "Dueño",
        ownerEmail,
        ownerPassword,
        plan,
      }),
    onSuccess: (data: any) => {
      onCreated?.();
      onClose();
      navigate(`/admin/businesses/${data.business.id}`);
    },
    onError: (e: any) => setError(e.message),
  });

  const selected = templates.find((t: any) => t.key === template);
  const canContinue = !!template;
  const canCreate = !!name.trim() && !!ownerEmail.trim() && !!ownerPassword.trim();

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Crear nuevo negocio"
      subtitle={step === 1 ? "Paso 1 de 2 — Elige una plantilla" : "Paso 2 de 2 — Datos del negocio y dueño"}
      size="lg"
      footer={
        <div className="flex items-center justify-between gap-2">
          <div className="text-xs text-slate-500">
            {step === 1 ? (
              <span className="inline-flex items-center gap-1"><Sparkles className="h-3.5 w-3.5 text-brand-500" /> La plantilla carga datos demo listos para usar.</span>
            ) : (
              <span>Se creará el negocio y la cuenta del dueño.</span>
            )}
          </div>
          <div className="flex items-center gap-2">
            {step === 2 && (
              <button onClick={() => setStep(1)} className="btn btn-ghost">Atrás</button>
            )}
            {step === 1 ? (
              <button onClick={() => canContinue && setStep(2)} className="btn btn-primary" disabled={!canContinue}>
                Continuar <ChevronRight className="h-4 w-4" />
              </button>
            ) : (
              <button onClick={() => mut.mutate()} className="btn btn-primary" disabled={!canCreate || mut.isPending}>
                {mut.isPending ? <Spinner /> : <Wand2 className="h-4 w-4" />} Crear negocio
              </button>
            )}
          </div>
        </div>
      }
    >
      {error && (
        <div className="mb-4 rounded-lg bg-rose-50 px-3 py-2 text-sm font-medium text-rose-700">{error}</div>
      )}

      {step === 1 ? (
        <div>
          <label className="label">Plantilla de demostración</label>
          {!templates.length ? (
            <div className="flex h-32 items-center justify-center"><Spinner /></div>
          ) : (
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              {templates.map((t: any) => {
                const on = template === t.key;
                return (
                  <button
                    key={t.key}
                    type="button"
                    onClick={() => setTemplate(t.key)}
                    className={cn(
                      "relative flex flex-col gap-1 rounded-xl border-2 p-3 text-left transition-all",
                      on ? "border-brand-500 bg-brand-50/50 shadow-soft" : "border-slate-200 hover:border-slate-300 hover:bg-slate-50"
                    )}
                  >
                    {on && (
                      <span className="absolute right-2 top-2 flex h-5 w-5 items-center justify-center rounded-full bg-brand-500 text-white">
                        <Check className="h-3 w-3" />
                      </span>
                    )}
                    <div className="flex items-center gap-2">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-white text-brand-600 shadow-soft">
                        <Building2 className="h-4 w-4" />
                      </div>
                      <span className="font-bold text-slate-900">{t.name}</span>
                    </div>
                    <p className="text-[11px] text-slate-500">{t.description}</p>
                    <div className="mt-1 flex gap-2 text-[10px] font-semibold text-slate-400">
                      <span>{t.employees} esp.</span>
                      <span>·</span>
                      <span>{t.services} serv.</span>
                      <span>·</span>
                      <span>{t.clients} clientes</span>
                    </div>
                  </button>
                );
              })}
            </div>
          )}
          <p className="mt-3 text-[11px] text-slate-400">
            Las plantillas crean empleados, servicios y clientes demo, además de citas pasadas y próximas para que el panel tenga datos desde el minuto uno.
            <strong> Blank</strong> crea un negocio vacío para configurar desde cero.
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {selected && (
            <div className="flex items-center gap-2 rounded-xl bg-brand-50 px-3 py-2 text-xs">
              <Sparkles className="h-3.5 w-3.5 text-brand-500" />
              <span className="text-brand-700">
                Plantilla: <strong>{selected.name}</strong> — {selected.employees} empleados, {selected.services} servicios, {selected.clients} clientes
              </span>
              <button onClick={() => setStep(1)} className="ml-auto font-semibold text-brand-600 hover:underline">cambiar</button>
            </div>
          )}
          <div className="grid gap-3 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <label className="label">Nombre del negocio *</label>
              <div className="relative">
                <Building2 className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input className="input pl-9" value={name} onChange={(e) => setName(e.target.value)} placeholder="Ej. Lumière Estética & Spa" />
              </div>
            </div>
            <div>
              <label className="label">Industria / Rubro</label>
              <input className="input" value={industry} onChange={(e) => setIndustry(e.target.value)} placeholder="Estética, Barbería, Dental…" />
            </div>
            <div>
              <label className="label">Plan</label>
              <div className="flex gap-1.5">
                {PLAN_OPTIONS.map((p) => (
                  <button
                    key={p.value}
                    type="button"
                    onClick={() => setPlan(p.value)}
                    className={cn(
                      "flex-1 rounded-lg border px-2 py-1.5 text-xs font-semibold transition-colors",
                      plan === p.value ? "border-brand-500 bg-brand-50 text-brand-700" : "border-slate-200 text-slate-600 hover:bg-slate-50"
                    )}
                  >
                    {p.label}
                    <span className="block text-[9px] font-normal text-slate-400">{p.desc}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>

          <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3">
            <div className="mb-2 flex items-center gap-1.5 text-xs font-bold text-slate-700">
              <UserPlus className="h-3.5 w-3.5" /> Cuenta del dueño
            </div>
            <div className="grid gap-3 sm:grid-cols-2">
              <div>
                <label className="label">Nombre del dueño</label>
                <input className="input" value={ownerName} onChange={(e) => setOwnerName(e.target.value)} placeholder="Dueño" />
              </div>
              <div>
                <label className="label">Correo *</label>
                <div className="relative">
                  <Mail className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                  <input className="input pl-9" type="email" value={ownerEmail} onChange={(e) => setOwnerEmail(e.target.value)} placeholder="dueno@negocio.com" />
                </div>
              </div>
              <div>
                <label className="label">Contraseña</label>
                <div className="relative">
                  <Lock className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                  <input className="input pl-9" value={ownerPassword} onChange={(e) => setOwnerPassword(e.target.value)} placeholder="demo1234" />
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </Modal>
  );
}
