"use client";

import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import clsx from "clsx";
import { CheckCircle2, Copy } from "lucide-react";
import { api } from "@/lib/api";
import type { AppConfig } from "@/lib/types";
import { buildInstallEnvSnippet, editionAddonLabel, INSTALL_EDITIONS, normalizeProductEdition, type BrandingDraft } from "@/lib/editions";

type InstallSetupPanelProps = {
  config?: AppConfig;
  title?: string;
  subtitle?: string;
  compact?: boolean;
};

const BRANDING_PRESETS: Array<{ id: string; label: string; value: BrandingDraft }> = [
  {
    id: "zimphony",
    label: "Zimphony Webmail",
    value: {
      name: "Zimphony Webmail",
      tagline: "Business email that grows with you.",
      logoUrl: "",
      faviconUrl: "",
      logoAlt: "Zimphony Webmail logo",
    },
  },
  {
    id: "clean",
    label: "Clean",
    value: {
      name: "Your Brand Mail",
      tagline: "Modern mail for teams that move fast.",
      logoUrl: "",
      faviconUrl: "",
      logoAlt: "Brand logo",
    },
  },
  {
    id: "comfort",
    label: "Comfort",
    value: {
      name: "Your Workspace",
      tagline: "Comfortable, reliable, and easy to trust.",
      logoUrl: "",
      faviconUrl: "",
      logoAlt: "Brand logo",
    },
  },
];

function providerLabel(value?: string | null) {
  const normalized = (value || "").trim().toLowerCase();
  if (!normalized || normalized === "none") return "none";
  if (normalized === "zimbra" || normalized === "native_zimbra") return "Mail Server";
  if (normalized === "google") return "Google";
  return "Provider";
}

export function InstallSetupPanel({ config, title, subtitle, compact = false }: InstallSetupPanelProps) {
  const appConfig = useQuery({
    queryKey: ["install-setup-config"],
    queryFn: () => api.config(),
    staleTime: 5 * 60_000,
    retry: false,
    enabled: !config,
  });
  const [copyNotice, setCopyNotice] = useState("");
  const resolvedConfig = config ?? appConfig.data;
  const [branding, setBranding] = useState<BrandingDraft>({
    name: "Zimphony Webmail",
    tagline: "Business email that grows with you.",
    logoUrl: "",
    faviconUrl: "",
    logoAlt: "Zimphony Webmail logo",
  });
  const activeEdition = normalizeProductEdition(resolvedConfig?.product.edition || "mail_only");
  const product = resolvedConfig?.product;
  const envSnippet = useMemo(() => buildInstallEnvSnippet(activeEdition, branding), [activeEdition, branding]);
  const brandingSnippet = useMemo(
    () =>
      [
        `BRAND_NAME=${branding.name}`,
        `BRAND_TAGLINE=${branding.tagline}`,
        `BRAND_LOGO_URL=${branding.logoUrl}`,
        `BRAND_LOGO_ALT=${branding.logoAlt}`,
        `BRAND_FAVICON_URL=${branding.faviconUrl}`,
      ].join("\n"),
    [branding]
  );

  useEffect(() => {
    if (!resolvedConfig?.branding) return;
    setBranding((current) => ({
      name: resolvedConfig.branding.name || current.name,
      tagline: resolvedConfig.branding.tagline || current.tagline,
      logoUrl: resolvedConfig.branding.logo_url || current.logoUrl,
      faviconUrl: resolvedConfig.branding.favicon_url || current.faviconUrl,
      logoAlt: resolvedConfig.branding.logo_alt || current.logoAlt,
    }));
  }, [resolvedConfig]);

  function copyText(label: string, text: string) {
    void navigator.clipboard.writeText(text).then(() => {
      setCopyNotice(`${label} copied`);
    });
  }

  function applyPreset(preset: BrandingDraft) {
    setBranding(preset);
    setCopyNotice(`Branding preset applied`);
  }

  return (
    <section className={clsx("grid gap-4 rounded-xl border border-slate-200/80 bg-white p-6 shadow-soft", compact && "p-4")}>
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Install setup</p>
          <h2 className={clsx("font-black text-slate-950", compact ? "text-xl" : "text-2xl")}>{title || "Webmail edition and environment"}</h2>
          <p className="mt-2 max-w-3xl text-sm leading-7 text-slate-600">
            {subtitle || "This install uses one codebase. Choose the webmail edition once, set the env values below, then deploy the same build on the customer server."}
          </p>
        </div>
        <button
          type="button"
          onClick={() => copyText("Current setup", envSnippet)}
          className="theme-button-soft h-10 px-4 text-sm"
          disabled={!product}
        >
          <Copy size={16} />
          Copy env
        </button>
      </div>

      {copyNotice ? <p className="text-sm font-semibold text-emerald-700">{copyNotice}</p> : null}

      <div className="grid gap-4 rounded-xl border border-slate-200 bg-slate-50 p-4">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="text-sm font-black text-slate-900">Branding preset</p>
            <p className="text-xs font-semibold leading-6 text-slate-500">Choose a starter look, then edit the branding fields below.</p>
          </div>
          <div className="flex flex-wrap gap-2">
            {BRANDING_PRESETS.map((preset) => (
              <button
                key={preset.id}
                type="button"
                onClick={() => applyPreset(preset.value)}
                className="theme-button-soft h-9 px-3 text-xs"
              >
                {preset.label}
              </button>
            ))}
            <button
              type="button"
              onClick={() => applyPreset({ name: "", tagline: "", logoUrl: "", faviconUrl: "", logoAlt: "" })}
              className="theme-button-soft h-9 px-3 text-xs"
            >
              Clear
            </button>
          </div>
        </div>

        <div className={clsx("grid gap-3", compact ? "md:grid-cols-1" : "md:grid-cols-2")}>
          <label className="grid gap-2 text-sm font-semibold text-slate-700">
            Brand name
            <input
              value={branding.name}
              onChange={(event) => setBranding((current) => ({ ...current, name: event.target.value }))}
              className="field h-11 px-4"
              placeholder="Zimphony Webmail"
            />
          </label>
          <label className="grid gap-2 text-sm font-semibold text-slate-700">
            Brand tagline
            <input
              value={branding.tagline}
              onChange={(event) => setBranding((current) => ({ ...current, tagline: event.target.value }))}
              className="field h-11 px-4"
              placeholder="Business email that stays calm and clear."
            />
          </label>
          <label className="grid gap-2 text-sm font-semibold text-slate-700">
            Logo URL
            <input
              value={branding.logoUrl}
              onChange={(event) => setBranding((current) => ({ ...current, logoUrl: event.target.value }))}
              className="field h-11 px-4"
              placeholder="https://example.com/logo.png"
            />
          </label>
          <label className="grid gap-2 text-sm font-semibold text-slate-700">
            Favicon URL
            <input
              value={branding.faviconUrl}
              onChange={(event) => setBranding((current) => ({ ...current, faviconUrl: event.target.value }))}
              className="field h-11 px-4"
              placeholder="https://example.com/favicon.png"
            />
          </label>
        </div>
        <label className="grid gap-2 text-sm font-semibold text-slate-700">
          Logo alt text
          <input
            value={branding.logoAlt}
            onChange={(event) => setBranding((current) => ({ ...current, logoAlt: event.target.value }))}
            className="field h-11 px-4"
            placeholder="Brand logo"
          />
        </label>
        <div className="grid gap-3 rounded-xl border border-slate-200 bg-white p-4">
          <div className="flex items-center justify-between gap-3">
            <p className="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Preview</p>
            <button
              type="button"
              onClick={() => copyText("Branding block", brandingSnippet)}
              className="theme-button-soft h-8 px-3 text-xs"
            >
              <Copy size={14} />
              Copy branding
            </button>
          </div>
          <div className="grid gap-3 md:grid-cols-[auto_1fr] md:items-center">
            <div className="flex h-16 w-16 items-center justify-center overflow-hidden rounded-xl border border-slate-200 bg-slate-50">
              {branding.logoUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={branding.logoUrl}
                  alt={branding.logoAlt || branding.name || "Brand logo"}
                  onError={(event) => {
                    const image = event.currentTarget;
                    if (image.src.endsWith("/brand-logo.png")) return;
                    image.src = "/brand-logo.png";
                  }}
                  className="h-full w-full object-contain"
                />
              ) : (
                <span className="text-[10px] font-black uppercase tracking-[0.16em] text-slate-400">Logo</span>
              )}
            </div>
            <div className="grid gap-1">
              <strong className="text-lg font-black text-slate-950">{branding.name || "Zimphony Webmail"}</strong>
              <p className="text-sm leading-6 text-slate-600">{branding.tagline || "Business email that grows with you."}</p>
            </div>
          </div>
        </div>
      </div>

      <div className={clsx("grid gap-3", compact ? "md:grid-cols-1" : "md:grid-cols-3")}>
        {INSTALL_EDITIONS.map((item) => (
          <button
            key={item.id}
            type="button"
            onClick={() => copyText(item.title, buildInstallEnvSnippet(item.id, branding))}
            className={clsx(
              "grid gap-3 rounded-xl border p-4 text-left transition",
              activeEdition === item.id
                ? "border-[color-mix(in_srgb,var(--accent)_22%,white)] bg-[color-mix(in_srgb,var(--accent)_8%,white)]"
                : "border-slate-200 bg-slate-50 hover:border-[color-mix(in_srgb,var(--accent)_18%,white)] hover:bg-white"
            )}
          >
            <div className="flex items-center justify-between gap-2">
              <strong className="text-sm font-black text-slate-950">{item.title}</strong>
              {activeEdition === item.id ? <CheckCircle2 size={16} className="text-[var(--accent)]" /> : null}
            </div>
            <p className="text-xs leading-6 text-slate-500">{item.description}</p>
            <pre className="overflow-auto rounded-lg border border-slate-200 bg-white p-3 text-[11px] leading-5 text-slate-600">{buildInstallEnvSnippet(item.id, branding)}</pre>
          </button>
        ))}
      </div>

      <div className={clsx("grid gap-3", compact ? "md:grid-cols-1" : "md:grid-cols-2")}>
          <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
            <p className="text-sm font-black text-slate-900">Selected edition</p>
            <p className="mt-1 text-sm font-semibold text-slate-600">{product?.name || "Loading product profile..."}</p>
            <p className="mt-2 text-xs font-semibold text-slate-500">
              Mode: {editionAddonLabel(product?.edition)} · mail core {providerLabel(product?.providers.mail)} · calendar {providerLabel(product?.providers.calendar)} · drive {providerLabel(product?.providers.drive)}
            </p>
          </div>
        <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
          <p className="text-sm font-black text-slate-900">Required install checklist</p>
          <ul className="mt-2 grid gap-2 text-sm font-semibold text-slate-600">
            <li>1. Set `PRODUCT_EDITION` before first deploy.</li>
            <li>2. Fill the webmail host and Mail Server URL.</li>
              <li>3. Add addon credentials only for the selected edition.</li>
            <li>4. Run the edition-specific install script.</li>
          </ul>
        </div>
      </div>
    </section>
  );
}
