"use client";

import { useEffect, useState, useCallback } from "react";
import { Palette, Globe, FileText, Monitor, Lock } from "lucide-react";
import { usePlan, usePlanContext } from "@/context/plan-context";
import { useBrand } from "@/context/brand-context";
import { planAtLeast } from "@/lib/plan-config";

interface WhiteLabelConfig {
  id: string;
  enabled: boolean;
  agencyName: string | null;
  logoUrl: string | null;
  logoDarkUrl: string | null;
  faviconUrl: string | null;
  primaryColor: string | null;
  secondaryColor: string | null;
  accentColor: string | null;
  fontFamily: string | null;
  supportEmail: string | null;
  removeMeseoBranding: boolean;
}

const FONT_OPTIONS = [
  { value: "", label: "System default" },
  { value: "inter", label: "Inter" },
  { value: "geist", label: "Geist" },
  { value: "roboto", label: "Roboto" },
  { value: "lato", label: "Lato" },
  { value: "open-sans", label: "Open Sans" },
];

function ColorInput({
  label,
  value,
  onChange,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <div>
      <label className="block text-xs font-semibold text-slate-600 mb-1">{label}</label>
      <div className="flex items-center gap-2">
        <input
          type="color"
          value={value || "#000000"}
          onChange={(e) => onChange(e.target.value)}
          className="w-9 h-9 rounded border border-slate-200 cursor-pointer p-0.5"
        />
        <input
          type="text"
          value={value || ""}
          onChange={(e) => onChange(e.target.value)}
          placeholder="#000000"
          className="flex-1 px-3 py-2 border border-slate-200 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-500/30"
        />
      </div>
    </div>
  );
}

function StubSection({ icon: Icon, title, description }: { icon: React.ElementType; title: string; description: string }) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden opacity-60">
      <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
        <Icon className="w-4 h-4 text-slate-400" />
        <h2 className="font-bold text-slate-700 text-sm">{title}</h2>
        <span className="ml-auto text-[10px] font-bold uppercase tracking-wider text-slate-400 bg-slate-100 rounded-full px-2.5 py-0.5">
          Coming Soon
        </span>
      </div>
      <div className="px-6 py-6 text-center">
        <Lock className="w-5 h-5 text-slate-300 mx-auto mb-2" />
        <p className="text-sm text-slate-400">{description}</p>
      </div>
    </div>
  );
}

export default function WhiteLabelTab() {
  const { plan, loading: planLoading } = usePlan();
  const { openUpgrade } = usePlanContext();
  const { orgId } = useBrand();

  const [userRole, setUserRole] = useState<string | null>(null);
  const [roleLoading, setRoleLoading] = useState(true);
  const [config, setConfig] = useState<WhiteLabelConfig | null>(null);
  const [configLoading, setConfigLoading] = useState(true);

  // Form state (mirrors WhiteLabelConfig fields)
  const [enabled, setEnabled] = useState(false);
  const [agencyName, setAgencyName] = useState("");
  const [logoUrl, setLogoUrl] = useState("");
  const [logoDarkUrl, setLogoDarkUrl] = useState("");
  const [faviconUrl, setFaviconUrl] = useState("");
  const [primaryColor, setPrimaryColor] = useState("");
  const [secondaryColor, setSecondaryColor] = useState("");
  const [accentColor, setAccentColor] = useState("");
  const [fontFamily, setFontFamily] = useState("");
  const [supportEmail, setSupportEmail] = useState("");
  const [removeMeseoBranding, setRemoveMeseoBranding] = useState(false);

  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [savedAt, setSavedAt] = useState<Date | null>(null);

  // Resolve the calling user's role in the current org
  useEffect(() => {
    if (!orgId) return;
    setRoleLoading(true);
    fetch(`/api/organizations/members?orgId=${orgId}`)
      .then((r) => r.json())
      .then((members: Array<{ user: { id: string }; role: string }>) => {
        // The API returns all members; find the current user by matching
        // against the config record (we don't have user.id on the client
        // directly, so we check via GET /api/white-label which is gated).
        // Use GET /api/me instead for the current user's id.
        return fetch("/api/me").then((r) => r.json()).then((me: { user?: { id: string } }) => {
          const myId = me?.user?.id;
          const mine = members.find((m) => m.user.id === myId);
          setUserRole(mine?.role ?? null);
        });
      })
      .catch(() => setUserRole(null))
      .finally(() => setRoleLoading(false));
  }, [orgId]);

  const loadConfig = useCallback(() => {
    setConfigLoading(true);
    fetch(`/api/white-label?orgId=${encodeURIComponent(orgId)}`)
      .then((r) => r.json())
      .then((data: { config: WhiteLabelConfig | null }) => {
        if (data.config) {
          const c = data.config;
          setConfig(c);
          setEnabled(c.enabled);
          setAgencyName(c.agencyName ?? "");
          setLogoUrl(c.logoUrl ?? "");
          setLogoDarkUrl(c.logoDarkUrl ?? "");
          setFaviconUrl(c.faviconUrl ?? "");
          setPrimaryColor(c.primaryColor ?? "");
          setSecondaryColor(c.secondaryColor ?? "");
          setAccentColor(c.accentColor ?? "");
          setFontFamily(c.fontFamily ?? "");
          setSupportEmail(c.supportEmail ?? "");
          setRemoveMeseoBranding(c.removeMeseoBranding ?? false);
        }
      })
      .catch(() => {})
      .finally(() => setConfigLoading(false));
  }, [orgId]);

  useEffect(() => {
    if (userRole && ["owner", "admin"].includes(userRole)) {
      loadConfig();
    } else if (!roleLoading) {
      setConfigLoading(false);
    }
  }, [userRole, roleLoading, loadConfig]);

  const handleSave = async () => {
    setSaving(true);
    setSaveError(null);
    try {
      const res = await fetch("/api/white-label", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          orgId,
          enabled,
          agencyName: agencyName || null,
          logoUrl: logoUrl || null,
          logoDarkUrl: logoDarkUrl || null,
          faviconUrl: faviconUrl || null,
          primaryColor: primaryColor || null,
          secondaryColor: secondaryColor || null,
          accentColor: accentColor || null,
          fontFamily: fontFamily || null,
          supportEmail: supportEmail || null,
          removeMeseoBranding,
        }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({})) as { error?: string };
        setSaveError(err?.error ?? "Save failed");
      } else {
        const data = await res.json() as { config: WhiteLabelConfig };
        setConfig(data.config);
        setSavedAt(new Date());
      }
    } catch {
      setSaveError("Network error — please try again");
    } finally {
      setSaving(false);
    }
  };

  // Loading state
  if (planLoading || roleLoading) {
    return (
      <div className="flex items-center justify-center py-16">
        <div className="w-5 h-5 border-2 border-slate-200 border-t-slate-600 rounded-full animate-spin" />
      </div>
    );
  }

  // Not an org admin
  if (!userRole || !["owner", "admin"].includes(userRole)) {
    return (
      <div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
        <Lock className="w-8 h-8 text-slate-300" />
        <div>
          <p className="text-sm font-semibold text-slate-700">Admin access required</p>
          <p className="text-xs text-slate-400 mt-1">
            White-label configuration is only available to organization owners and admins.
            Contact your org admin to make changes.
          </p>
        </div>
      </div>
    );
  }

  // Not on Agency or higher
  if (!plan || !planAtLeast(plan.effectivePlan, "agency")) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 py-16 text-center">
        <div className="w-12 h-12 rounded-xl bg-brand-50 border border-brand-200 flex items-center justify-center">
          <Palette className="w-6 h-6 text-brand-500" />
        </div>
        <div>
          <p className="text-sm font-semibold text-slate-800">White-label is an Agency feature</p>
          <p className="text-xs text-slate-500 mt-1 max-w-xs">
            Serve clients under your own brand with custom colors, logo, and domain.
            Available on the Agency plan and above.
          </p>
        </div>
        <button
          onClick={() => openUpgrade({ kind: "manual", recommendedPlan: "agency" })}
          className="inline-flex items-center gap-1.5 px-5 py-2.5 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700 transition-colors"
        >
          Upgrade to Agency
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Branding */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <Palette className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Branding</h2>
          <label className="ml-auto flex items-center gap-2 cursor-pointer">
            <span className="text-xs text-slate-500">White-label {enabled ? "enabled" : "disabled"}</span>
            <button
              type="button"
              role="switch"
              aria-checked={enabled}
              onClick={() => setEnabled(!enabled)}
              className={`relative inline-flex w-9 h-5 rounded-full transition-colors ${
                enabled ? "bg-brand-600" : "bg-slate-200"
              }`}
            >
              <span
                className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform ${
                  enabled ? "translate-x-4" : "translate-x-0"
                }`}
              />
            </button>
          </label>
        </div>

        <div className="px-6 py-5 space-y-5">
          {/* Agency name */}
          <div>
            <label className="block text-xs font-semibold text-slate-600 mb-1">Agency name</label>
            <input
              type="text"
              value={agencyName}
              onChange={(e) => setAgencyName(e.target.value)}
              placeholder="Acme SEO"
              className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/30"
            />
          </div>

          {/* Logos */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div>
              <label className="block text-xs font-semibold text-slate-600 mb-1">Logo URL (light)</label>
              <input
                type="url"
                value={logoUrl}
                onChange={(e) => setLogoUrl(e.target.value)}
                placeholder="https://..."
                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/30"
              />
              <p className="text-[10px] text-slate-400 mt-1">Used on light backgrounds</p>
            </div>
            <div>
              <label className="block text-xs font-semibold text-slate-600 mb-1">Logo URL (dark)</label>
              <input
                type="url"
                value={logoDarkUrl}
                onChange={(e) => setLogoDarkUrl(e.target.value)}
                placeholder="https://..."
                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/30"
              />
              <p className="text-[10px] text-slate-400 mt-1">Used on dark backgrounds</p>
            </div>
            <div>
              <label className="block text-xs font-semibold text-slate-600 mb-1">Favicon URL</label>
              <input
                type="url"
                value={faviconUrl}
                onChange={(e) => setFaviconUrl(e.target.value)}
                placeholder="https://..."
                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/30"
              />
              <p className="text-[10px] text-slate-400 mt-1">.ico or 32x32 PNG</p>
            </div>
          </div>

          {/* Colors */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <ColorInput label="Primary color" value={primaryColor} onChange={setPrimaryColor} />
            <ColorInput label="Secondary color" value={secondaryColor} onChange={setSecondaryColor} />
            <ColorInput label="Accent color" value={accentColor} onChange={setAccentColor} />
          </div>

          {/* Font + Support email */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-slate-600 mb-1">Font family</label>
              <select
                value={fontFamily}
                onChange={(e) => setFontFamily(e.target.value)}
                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/30 bg-white"
              >
                {FONT_OPTIONS.map((o) => (
                  <option key={o.value} value={o.value}>{o.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-slate-600 mb-1">Support email</label>
              <input
                type="email"
                value={supportEmail}
                onChange={(e) => setSupportEmail(e.target.value)}
                placeholder="support@youragency.com"
                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/30"
              />
            </div>
          </div>

          {/* Remove meSEO branding */}
          <label className="flex items-start gap-3 cursor-pointer">
            <input
              type="checkbox"
              checked={removeMeseoBranding}
              onChange={(e) => setRemoveMeseoBranding(e.target.checked)}
              className="mt-0.5 w-4 h-4 rounded border-slate-300 text-brand-600 focus:ring-brand-500"
            />
            <div>
              <p className="text-sm font-semibold text-slate-800">Remove meSEO branding</p>
              <p className="text-xs text-slate-500">
                Hides &ldquo;Powered by meSEO&rdquo; attribution from client-facing views and PDF exports.
              </p>
            </div>
          </label>

          {/* Save bar */}
          <div className="flex items-center gap-3 pt-2 border-t border-slate-100">
            <button
              onClick={handleSave}
              disabled={saving || configLoading}
              className="px-5 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700 disabled:opacity-50 transition-colors"
            >
              {saving ? "Saving..." : "Save branding"}
            </button>
            {saveError && <p className="text-xs text-red-600">{saveError}</p>}
            {savedAt && !saveError && (
              <p className="text-xs text-emerald-600">
                Saved {savedAt.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Stub sections */}
      <StubSection
        icon={Globe}
        title="Custom Domain"
        description="Point your own domain (e.g. reports.youragency.com) to your client portal. DNS verification and SSL provisioning coming soon."
      />
      <StubSection
        icon={Monitor}
        title="Preview"
        description="Live preview of how your white-label branding looks to clients. Available once branding is saved and enabled."
      />
      <StubSection
        icon={FileText}
        title="PDF Template"
        description="Upload a custom cover page and letterhead for report PDF exports. Requires white-label enabled."
      />
    </div>
  );
}
