"use client";

import { Check, ImageUp, LayoutPanelLeft, LayoutPanelTop, PanelLeft, PanelRight } from "lucide-react";
import { loginThemeNames, loginThemes, type LoginThemeName } from "@/lib/login-theme";

export type LoginDesignMode = "theme" | "custom";
export type LoginTemplateName = "panel-left" | "panel-right" | "centered" | "split";

export type LoginDesignerDraft = {
  mode: LoginDesignMode;
  theme: LoginThemeName;
  landscapeOnly: boolean;
  template: LoginTemplateName;
  backgroundColor: string;
  gradientColor: string;
  brandNameColor: string;
  taglineColor: string;
  supportingTextColor: string;
  boxTransparency: number;
};

const templates: Array<{ id: LoginTemplateName; name: string; detail: string; theme: LoginThemeName; icon: typeof PanelLeft }> = [
  { id: "panel-left", name: "Panel left", detail: "1600 x 1000 px", theme: "mint", icon: PanelLeft },
  { id: "panel-right", name: "Panel right", detail: "1600 x 1000 px", theme: "cyan", icon: PanelRight },
  { id: "centered", name: "Centered", detail: "1920 x 1080 px", theme: "indigo", icon: LayoutPanelTop },
  { id: "split", name: "Split view", detail: "1600 x 1000 px", theme: "sunset", icon: LayoutPanelLeft },
];

export function LoginDesigner({ draft, backgroundUrl, selectedFileName, busy, error, onChange, onFileChange, onSave }: {
  draft: LoginDesignerDraft;
  backgroundUrl: string;
  selectedFileName: string;
  busy: boolean;
  error: string;
  onChange: (next: LoginDesignerDraft) => void;
  onFileChange: (file: File | null) => void;
  onSave: () => void;
}) {
  const selectedTheme = loginThemes[draft.theme];
  return (
    <div className="mx-auto grid w-full max-w-[1180px] gap-5 pb-8">
      <div className="flex flex-wrap items-end justify-between gap-3 border-b border-slate-200 pb-4">
        <div>
          <h1 className="text-2xl font-black text-slate-950">Login Designer</h1>
          <p className="mt-1 text-sm font-semibold text-slate-600">Configure the sign-in page for this domain.</p>
        </div>
        <button type="button" className="theme-button h-10 px-5 text-sm" disabled={busy} onClick={onSave}>{busy ? "Saving..." : "Save design"}</button>
      </div>

      <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_360px]">
        <div className="grid content-start gap-6">
          <div className="inline-flex w-fit rounded-lg border border-slate-200 bg-white p-1">
            {(["theme", "custom"] as const).map((mode) => (
              <button key={mode} type="button" onClick={() => onChange({ ...draft, mode })} className={draft.mode === mode ? "rounded-md bg-[var(--accent)] px-4 py-2 text-sm font-black text-white" : "rounded-md px-4 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"}>
                {mode === "theme" ? "Built-in theme" : "Custom design"}
              </button>
            ))}
          </div>

          {draft.mode === "theme" ? (
            <fieldset className="grid gap-3">
              <legend className="text-sm font-black text-slate-900">Theme</legend>
              <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
                {loginThemeNames.map((name) => {
                  const theme = loginThemes[name];
                  const selected = draft.theme === name;
                  return <button key={name} type="button" aria-pressed={selected} onClick={() => onChange({ ...draft, theme: name, brandNameColor: theme.heading, taglineColor: theme.body, supportingTextColor: theme.supporting })} className={`relative overflow-hidden rounded-lg border bg-white text-left ${selected ? "border-[var(--accent)] ring-2 ring-[var(--accent)]" : "border-slate-200"}`}>
                    <span className="block aspect-[5/3] bg-cover bg-center" style={{ backgroundColor: theme.panel, backgroundImage: `url('${draft.landscapeOnly ? theme.landscapePreviewUrl : theme.previewUrl}')` }} />
                    <span className="flex items-center justify-between px-3 py-2 text-xs font-black text-slate-800">{theme.name}{selected ? <Check size={14} /> : null}</span>
                  </button>;
                })}
              </div>
              <label className="mt-1 flex items-center gap-3 text-sm font-bold text-slate-700"><input type="checkbox" checked={draft.landscapeOnly} onChange={(event) => onChange({ ...draft, landscapeOnly: event.target.checked })} className="h-4 w-4" />Landscape only</label>
            </fieldset>
          ) : (
            <>
              <fieldset className="grid gap-3">
                <legend className="text-sm font-black text-slate-900">Template</legend>
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
                  {templates.map((item) => {
                    const theme = loginThemes[item.theme];
                    const selected = draft.template === item.id;
                    const Icon = item.icon;
                    return <button key={item.id} type="button" onClick={() => onChange({ ...draft, template: item.id, theme: item.theme, backgroundColor: theme.canvas, gradientColor: theme.panel, brandNameColor: theme.heading, taglineColor: theme.body, supportingTextColor: theme.supporting })} className={`overflow-hidden rounded-lg border bg-white text-left ${selected ? "border-[var(--accent)] ring-2 ring-[var(--accent)]" : "border-slate-200"}`}>
                      <span className="relative block aspect-[5/3] bg-cover bg-center" style={{ backgroundColor: theme.panel, backgroundImage: `url('${theme.landscapePreviewUrl}')` }}><Icon className="absolute bottom-2 right-2 rounded bg-white/90 p-1 text-slate-700" size={24} /></span>
                      <span className="block px-3 py-2"><strong className="block text-xs text-slate-900">{item.name}</strong><span className="text-[11px] font-semibold text-slate-500">{item.detail}</span></span>
                    </button>;
                  })}
                </div>
              </fieldset>
              <div className="grid gap-4 sm:grid-cols-2">
                <ColorField label="Background color" value={draft.backgroundColor} onChange={(backgroundColor) => onChange({ ...draft, backgroundColor })} />
                <ColorField label="Gradient color" value={draft.gradientColor} onChange={(gradientColor) => onChange({ ...draft, gradientColor })} />
                <ColorField label="Brand name color" value={draft.brandNameColor} onChange={(brandNameColor) => onChange({ ...draft, brandNameColor })} />
                <ColorField label="Tagline color" value={draft.taglineColor} onChange={(taglineColor) => onChange({ ...draft, taglineColor })} />
                <ColorField label="Supporting text color" value={draft.supportingTextColor} onChange={(supportingTextColor) => onChange({ ...draft, supportingTextColor })} />
              </div>
              <label className="grid gap-2 text-sm font-black text-slate-800">Login box transparency
                <span className="flex h-11 items-center gap-3 rounded-lg border border-slate-200 bg-white px-3"><input type="range" min="0" max="30" step="1" value={draft.boxTransparency} onChange={(event) => onChange({ ...draft, boxTransparency: Number(event.target.value) })} className="min-w-0 flex-1 accent-[var(--accent)]" /><output className="w-12 text-right text-sm font-black text-slate-700">{draft.boxTransparency}%</output></span>
              </label>
              <label className="grid gap-2 text-sm font-black text-slate-800">Background image
                <span className="flex min-h-24 cursor-pointer items-center justify-center gap-3 rounded-lg border border-dashed border-slate-300 bg-white px-4 text-center text-sm font-bold text-slate-600 hover:border-[var(--accent)]"><ImageUp size={20} />{selectedFileName || "Choose PNG, JPG, or WEBP (up to 12 MB)"}<input type="file" accept="image/png,image/jpeg,image/webp" className="sr-only" onChange={(event) => onFileChange(event.target.files?.[0] || null)} /></span>
              </label>
            </>
          )}
          {error ? <p className="rounded-lg border border-rose-200 bg-rose-50 px-4 py-3 text-sm font-bold text-rose-700">{error}</p> : null}
        </div>

        <div className="lg:sticky lg:top-4 lg:self-start">
          <p className="mb-2 text-xs font-black uppercase text-slate-500">Preview</p>
          <div className="relative aspect-[10/7] overflow-hidden rounded-lg border border-slate-200 bg-cover bg-center shadow-soft" style={{ backgroundColor: draft.mode === "custom" ? draft.backgroundColor : selectedTheme.canvas, backgroundImage: draft.mode === "custom" && backgroundUrl ? `linear-gradient(135deg, ${draft.backgroundColor}88, ${draft.gradientColor}88), url('${backgroundUrl}')` : `url('${draft.landscapeOnly ? selectedTheme.landscapePreviewUrl : selectedTheme.previewUrl}')` }}>
            <div className={`absolute top-1/2 h-[72%] w-[38%] -translate-y-1/2 rounded-lg p-3 shadow-lg backdrop-blur-sm ${draft.mode === "custom" && draft.template === "panel-right" ? "right-5" : draft.mode === "custom" && draft.template === "centered" ? "left-1/2 -translate-x-1/2" : "left-5"}`} style={{ backgroundColor: `rgba(255,255,255,${draft.mode === "custom" ? (100 - draft.boxTransparency) / 100 : 0.95})` }}>
              <div className="mx-auto mb-3 h-8 w-8 rounded-full bg-slate-100" /><div className="mb-2 h-2 rounded bg-slate-200" /><div className="mb-2 h-6 rounded border border-slate-200" /><div className="mb-3 h-6 rounded border border-slate-200" /><div className="h-6 rounded" style={{ backgroundColor: selectedTheme.accent }} />
            </div>
            <div className={`absolute top-8 max-w-[48%] ${draft.mode === "custom" && draft.template === "panel-right" ? "left-6" : draft.mode === "custom" && draft.template === "centered" ? "hidden" : "right-6"}`}>
              <p className="text-lg font-black leading-tight" style={{ color: draft.brandNameColor }}>Company Webmail</p>
              <p className="mt-1 text-xs font-bold leading-4" style={{ color: draft.taglineColor }}>Business email that grows with you.</p>
              <p className="mt-1 text-[11px] font-semibold leading-4" style={{ color: draft.supportingTextColor }}>Fast, reliable, and built for everyday work.</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ColorField({ label, value, onChange }: { label: string; value: string; onChange: (value: string) => void }) {
  return <label className="grid gap-2 text-sm font-black text-slate-800">{label}<span className="flex h-11 items-center gap-2 rounded-lg border border-slate-200 bg-white px-2"><input type="color" value={value} onChange={(event) => onChange(event.target.value)} className="h-7 w-9 cursor-pointer border-0 bg-transparent p-0" /><input value={value} onChange={(event) => /^#[0-9a-fA-F]{0,6}$/.test(event.target.value) && onChange(event.target.value)} className="min-w-0 flex-1 bg-transparent font-mono text-sm uppercase outline-none" /></span></label>;
}
