import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { toast } from "sonner";
import { ExternalLink, Upload, Maximize2, Minimize2 } from "lucide-react";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? "";

interface Props {
  companyId: string;
  companyName: string;
}

const PreviewSection = ({ form, branding, companyName }: { form: any; branding: any; companyName: string }) => {
  const [expanded, setExpanded] = useState(false);

  // Scale factor: compact ~1/6, expanded ~1/3 of real site proportions
  // Real site: navbar 64px, hero 750px, card image 192px, card padding 20px
  const s = expanded ? 0.33 : 0.16;
  const navH = Math.round(64 * s);
  const heroH = Math.round(750 * s);
  const cardImgH = Math.round(192 * s);
  const cardPad = Math.max(4, Math.round(20 * s));
  const sectionPad = Math.max(8, Math.round(48 * s));
  const fontSize = expanded ? 12 : 9;
  const badgeSize = expanded ? 10 : 8;
  const titleSize = expanded ? 11 : 9;

  const sampleCards = [
    { badge: "NRSWA", title: "NRSWA Operative Training", days: 5, price: "£849.00" },
    { badge: "Smart Awards", title: "Safety Underground", days: 1, price: "£199.50" },
    { badge: "Smart Awards", title: "Safe Moving & Handling", days: 1, price: "£97.50" },
  ];

  return (
    <div className="border-t border-border pt-5 mt-2">
      <div className="flex items-center justify-between mb-3">
        <h3 className="text-sm font-semibold text-foreground">Homepage Preview</h3>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={() => setExpanded(!expanded)}
          className="gap-1.5 text-xs"
        >
          {expanded ? <Minimize2 className="w-3.5 h-3.5" /> : <Maximize2 className="w-3.5 h-3.5" />}
          {expanded ? "Collapse" : "Expand"}
        </Button>
      </div>
      <div
        className="rounded-xl border border-border overflow-hidden transition-all"
        style={{ backgroundColor: form.background_color, aspectRatio: expanded ? "16/10" : undefined }}
      >
        {/* Preview Navbar */}
        <div
          className="flex items-center justify-between px-4 border-b border-border/30"
          style={{ backgroundColor: form.background_color, height: navH }}
        >
          <div className="flex items-center gap-2">
            {branding?.logo_url && (
              <img src={branding.logo_url} alt="" style={{ height: navH * 0.6 }} className="object-contain" />
            )}
            <span style={{ color: form.font_color + "99", fontSize }}>
              {form.tagline || "Tagline"}
            </span>
          </div>
          <div className="flex gap-3" style={{ color: form.font_color + "99", fontSize }}>
            <span>Home</span>
            <span style={{ color: form.primary_color }}>Courses</span>
            <span>Contact</span>
          </div>
        </div>

        {/* Preview Hero — proportional to real 750px */}
        {branding?.hero_image_url ? (
          <img src={branding.hero_image_url} alt="" className="w-full object-cover" style={{ height: heroH }} />
        ) : (
          <div className="flex items-center justify-center" style={{ height: heroH, backgroundColor: form.secondary_color }}>
            <span style={{ color: form.font_color, fontSize: fontSize * 1.6, fontWeight: 700 }}>{companyName}</span>
          </div>
        )}

        {/* Preview Course Cards — 3-col grid matching real layout */}
        <div style={{ padding: sectionPad }}>
          <p style={{ color: form.font_color, fontSize: fontSize * 1.2, fontWeight: 600, marginBottom: sectionPad * 0.6 }}>Our Courses</p>
          <div className="grid grid-cols-3" style={{ gap: Math.max(4, Math.round(24 * s)) }}>
            {sampleCards.map((card, i) => (
              <div key={i} className="rounded-lg overflow-hidden" style={{ backgroundColor: form.card_color }}>
                <div style={{ height: cardImgH, backgroundColor: form.secondary_color }} />
                <div style={{ padding: cardPad }}>
                  <div className="rounded inline-block mb-1" style={{ backgroundColor: form.primary_color, color: "#fff", fontSize: badgeSize, padding: "1px 4px", lineHeight: 1.4 }}>
                    {card.badge}
                  </div>
                  <p style={{ color: form.card_font_color, fontSize: titleSize, fontWeight: 600, margin: "2px 0 4px", lineHeight: 1.3 }}>
                    {card.title}
                  </p>
                  <div className="flex justify-between items-center">
                    <span style={{ color: form.card_font_color + "99", fontSize: badgeSize }}>{card.days} day{card.days !== 1 ? "s" : ""}</span>
                    <span style={{ color: form.primary_color, fontSize: badgeSize, fontWeight: 700 }}>{card.price}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

const CompanyBrandingPanel = ({ companyId, companyName }: Props) => {
  const queryClient = useQueryClient();

  const { data: branding } = useQuery({
    queryKey: ["company-branding", companyId],
    queryFn: async (): Promise<any> => {
      const res = await fetch(`/api/admin/companies/${companyId}/branding`);
      if (!res.ok) return null;
      return res.json();
    },
  });

  const { data: stripeConfig } = useQuery({
    queryKey: ["company-stripe-config", companyId],
    queryFn: async (): Promise<any> => {
      const res = await fetch(`/api/admin/companies/${companyId}/stripe-config`);
      if (!res.ok) return null;
      return res.json();
    },
  });

  const [form, setForm] = useState({
    subdomain: "",
    primary_color: "#1E40AF",
    secondary_color: "#1E3A5F",
    background_color: "#0A0F1C",
    font_color: "#FFFFFF",
    card_color: "#0F172A",
    tagline: "",
    card_font_color: "#FFFFFF",
    is_active: false,
    contact_email: "",
    contact_phone: "",
    contact_address: "",
    opening_hours: "",
    hero_video_url: "",
  });
  const [heroMediaTab, setHeroMediaTab] = useState<"image" | "video">("image");
  const [videoUrlInput, setVideoUrlInput] = useState("");

  useEffect(() => {
    if (branding) {
      const vid = (branding as any).hero_video_url || "";
      setForm({
        subdomain: branding.subdomain || "",
        primary_color: branding.primary_color || "#1E40AF",
        secondary_color: branding.secondary_color || "#1E3A5F",
        background_color: branding.background_color || "#0A0F1C",
        font_color: branding.font_color || "#FFFFFF",
        card_color: branding.card_color || "#0F172A",
        tagline: branding.tagline || "",
        card_font_color: branding.card_font_color || "#FFFFFF",
        is_active: branding.is_active,
        contact_email: branding.contact_email || "",
        contact_phone: branding.contact_phone || "",
        contact_address: branding.contact_address || "",
        opening_hours: branding.opening_hours || "",
        hero_video_url: vid,
      });
      setVideoUrlInput(vid);
      if (vid) setHeroMediaTab("video");
    }
  }, [branding]);

  const upsertMutation = useMutation({
    mutationFn: async () => {
      const payload = {
        company_id: companyId,
        subdomain: form.subdomain.trim().toLowerCase() || null,
        primary_color: form.primary_color,
        secondary_color: form.secondary_color,
        background_color: form.background_color,
        font_color: form.font_color,
        card_color: form.card_color,
        tagline: form.tagline.trim() || null,
        is_active: form.is_active,
        card_font_color: form.card_font_color || null,
        contact_email: form.contact_email.trim() || null,
        contact_phone: form.contact_phone.trim() || null,
        contact_address: form.contact_address.trim() || null,
        opening_hours: form.opening_hours.trim() || null,
        hero_video_url: form.hero_video_url.trim() || null,
      };
      const res = await fetch(`/api/admin/companies/${companyId}/branding`, {
        method: branding ? "PUT" : "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error("Failed to save branding");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["company-branding", companyId] });
      toast.success("Branding saved");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const [uploading, setUploading] = useState(false);
  const [stripePublishableKey, setStripePublishableKey] = useState("");
  const [stripeSecretKey, setStripeSecretKey] = useState("");
  const [savingStripe, setSavingStripe] = useState(false);

  useEffect(() => {
    if (stripeConfig) {
      setStripePublishableKey(stripeConfig.stripe_publishable_key || "");
      setStripeSecretKey(stripeConfig.stripe_secret_key || "");
    }
  }, [stripeConfig]);

  const handleSaveStripeConfig = async () => {
    setSavingStripe(true);
    try {
      const res = await fetch(`/api/admin/companies/${companyId}/stripe-config`, {
        method: stripeConfig ? "PUT" : "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({
          company_id: companyId,
          stripe_publishable_key: stripePublishableKey.trim(),
          stripe_secret_key: stripeSecretKey.trim(),
        }),
      });
      if (!res.ok) throw new Error("Failed to save Stripe keys");
      queryClient.invalidateQueries({ queryKey: ["company-stripe-config", companyId] });
      toast.success("Stripe keys saved");
    } catch (err: any) {
      toast.error(err.message);
    } finally {
      setSavingStripe(false);
    }
  };

  const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("type", "logo");
      const res = await fetch(`/api/admin/companies/${companyId}/branding/upload`, {
        method: "POST",
        headers: { "X-CSRF-TOKEN": csrfToken() },
        body: fd,
      });
      if (!res.ok) throw new Error("Upload failed");
      queryClient.invalidateQueries({ queryKey: ["company-branding", companyId] });
      toast.success("Logo uploaded");
    } catch (err: any) {
      toast.error(err.message);
    } finally {
      setUploading(false);
    }
  };

  const handleVideoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("type", "hero_video");
      const res = await fetch(`/api/admin/companies/${companyId}/branding/upload`, {
        method: "POST",
        headers: { "X-CSRF-TOKEN": csrfToken() },
        body: fd,
      });
      if (!res.ok) throw new Error("Upload failed");
      const result = await res.json().catch(() => ({}));
      const videoUrl = result.url || "";
      setVideoUrlInput(videoUrl);
      setForm(f => ({ ...f, hero_video_url: videoUrl }));
      queryClient.invalidateQueries({ queryKey: ["company-branding", companyId] });
      toast.success("Hero video uploaded");
    } catch (err: any) {
      toast.error(err.message);
    } finally {
      setUploading(false);
    }
  };

  const handleVideoUrlSave = async () => {
    const url = videoUrlInput.trim();
    setForm(f => ({ ...f, hero_video_url: url }));
    try {
      const res = await fetch(`/api/admin/companies/${companyId}/branding`, {
        method: "PUT",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
        body: JSON.stringify({ hero_video_url: url || null }),
      });
      if (!res.ok) throw new Error("Failed to save video URL");
      queryClient.invalidateQueries({ queryKey: ["company-branding", companyId] });
      toast.success("Hero video URL saved");
    } catch (err: any) {
      toast.error(err.message);
    }
  };

  const handleHeroUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("type", "hero_image");
      const res = await fetch(`/api/admin/companies/${companyId}/branding/upload`, {
        method: "POST",
        headers: { "X-CSRF-TOKEN": csrfToken() },
        body: fd,
      });
      if (!res.ok) throw new Error("Upload failed");
      queryClient.invalidateQueries({ queryKey: ["company-branding", companyId] });
      toast.success("Hero image uploaded");
    } catch (err: any) {
      toast.error(err.message);
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="bg-card border border-border rounded-xl p-6">
      <h2 className="text-lg font-semibold text-foreground mb-1">White-Label Branding</h2>
      <p className="text-sm text-muted-foreground mb-6">
        Configure the subdomain booking engine for {companyName}.
      </p>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          upsertMutation.mutate();
        }}
        className="space-y-5"
      >
        {/* Subdomain */}
        <div className="space-y-2">
          <Label>Subdomain</Label>
          <div className="flex items-center gap-2">
            <Input
              value={form.subdomain}
              onChange={(e) => setForm(f => ({ ...f, subdomain: e.target.value }))}
              placeholder="locktel"
              maxLength={50}
              className="max-w-xs"
            />
            <span className="text-sm text-muted-foreground">.yourdomain.com</span>
          </div>
        </div>

        {/* Tagline */}
        <div className="space-y-2">
          <Label>Tagline</Label>
          <Input
            value={form.tagline}
            onChange={(e) => setForm(f => ({ ...f, tagline: e.target.value }))}
            placeholder="Professional training solutions"
            maxLength={200}
          />
        </div>

        {/* Colour pickers */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="space-y-2">
            <Label>Primary Colour</Label>
            <p className="text-xs text-muted-foreground">
              Used for buttons, links, badges, and key action elements across the site.
            </p>
            <div className="flex items-center gap-2">
              <input
                type="color"
                value={form.primary_color}
                onChange={(e) => setForm(f => ({ ...f, primary_color: e.target.value }))}
                className="w-10 h-10 rounded border border-border cursor-pointer"
              />
              <Input
                value={form.primary_color}
                onChange={(e) => setForm(f => ({ ...f, primary_color: e.target.value }))}
                className="max-w-[100px]"
                maxLength={7}
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Secondary Colour</Label>
            <p className="text-xs text-muted-foreground">
              Used for hover states, card backgrounds, and subtle accent areas.
            </p>
            <div className="flex items-center gap-2">
              <input
                type="color"
                value={form.secondary_color}
                onChange={(e) => setForm(f => ({ ...f, secondary_color: e.target.value }))}
                className="w-10 h-10 rounded border border-border cursor-pointer"
              />
              <Input
                value={form.secondary_color}
                onChange={(e) => setForm(f => ({ ...f, secondary_color: e.target.value }))}
                className="max-w-[100px]"
                maxLength={7}
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Background Colour</Label>
            <p className="text-xs text-muted-foreground">
              The main page background colour for the entire site.
            </p>
            <div className="flex items-center gap-2">
              <input
                type="color"
                value={form.background_color}
                onChange={(e) => setForm(f => ({ ...f, background_color: e.target.value }))}
                className="w-10 h-10 rounded border border-border cursor-pointer"
              />
              <Input
                value={form.background_color}
                onChange={(e) => setForm(f => ({ ...f, background_color: e.target.value }))}
                className="max-w-[100px]"
                maxLength={7}
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Font Colour</Label>
            <p className="text-xs text-muted-foreground">
              Body text colour used for headings and paragraphs.
            </p>
            <div className="flex items-center gap-2">
              <input
                type="color"
                value={form.font_color}
                onChange={(e) => setForm(f => ({ ...f, font_color: e.target.value }))}
                className="w-10 h-10 rounded border border-border cursor-pointer"
              />
              <Input
                value={form.font_color}
                onChange={(e) => setForm(f => ({ ...f, font_color: e.target.value }))}
                className="max-w-[100px]"
                maxLength={7}
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Card Colour</Label>
            <p className="text-xs text-muted-foreground">
              Background colour for course cards on the homepage.
            </p>
            <div className="flex items-center gap-2">
              <input
                type="color"
                value={form.card_color}
                onChange={(e) => setForm(f => ({ ...f, card_color: e.target.value }))}
                className="w-10 h-10 rounded border border-border cursor-pointer"
              />
              <Input
                value={form.card_color}
                onChange={(e) => setForm(f => ({ ...f, card_color: e.target.value }))}
                className="max-w-[100px]"
                maxLength={7}
              />
            </div>
          </div>
          <div className="space-y-2">
            <Label>Card Font Colour</Label>
            <p className="text-xs text-muted-foreground">
              Text colour used inside course cards.
            </p>
            <div className="flex items-center gap-2">
              <input
                type="color"
                value={form.card_font_color}
                onChange={(e) => setForm(f => ({ ...f, card_font_color: e.target.value }))}
                className="w-10 h-10 rounded border border-border cursor-pointer"
              />
              <Input
                value={form.card_font_color}
                onChange={(e) => setForm(f => ({ ...f, card_font_color: e.target.value }))}
                className="max-w-[100px]"
                maxLength={7}
              />
            </div>
          </div>
        </div>

        {/* Live Preview */}
        <PreviewSection
          form={form}
          branding={branding}
          companyName={companyName}
        />

        {/* Logo & Hero Media */}
        <div className="grid grid-cols-2 gap-4">
          {/* Logo upload */}
          <div className="space-y-2">
            <Label>Company Logo</Label>
            {branding?.logo_url && (
              <img src={branding.logo_url} alt="Logo" className="h-12 object-contain mb-2 bg-secondary/50 rounded p-1" />
            )}
            <label className="flex items-center gap-2 cursor-pointer text-sm text-primary hover:underline">
              <Upload className="w-4 h-4" />
              {uploading ? "Uploading..." : "Upload Logo"}
              <input type="file" accept="image/*" className="hidden" onChange={handleLogoUpload} disabled={uploading} />
            </label>
          </div>

          {/* Hero media — image or video */}
          <div className="space-y-2">
            <Label>Hero Media</Label>
            {/* Tab toggle */}
            <div className="flex rounded-lg border border-border overflow-hidden w-fit text-xs">
              <button
                type="button"
                onClick={() => setHeroMediaTab("image")}
                className={`px-3 py-1.5 font-medium transition-colors ${heroMediaTab === "image" ? "bg-primary text-primary-foreground" : "bg-background text-muted-foreground hover:bg-muted"}`}
              >
                Image
              </button>
              <button
                type="button"
                onClick={() => setHeroMediaTab("video")}
                className={`px-3 py-1.5 font-medium transition-colors ${heroMediaTab === "video" ? "bg-primary text-primary-foreground" : "bg-background text-muted-foreground hover:bg-muted"}`}
              >
                Video
              </button>
            </div>

            {heroMediaTab === "image" ? (
              <div className="space-y-1">
                {branding?.hero_image_url && (
                  <img src={branding.hero_image_url} alt="Hero" className="h-12 w-full object-cover mb-2 rounded" />
                )}
                <label className="flex items-center gap-2 cursor-pointer text-sm text-primary hover:underline">
                  <Upload className="w-4 h-4" />
                  {uploading ? "Uploading..." : "Upload Hero Image"}
                  <input type="file" accept="image/*" className="hidden" onChange={handleHeroUpload} disabled={uploading} />
                </label>
              </div>
            ) : (
              <div className="space-y-2">
                {form.hero_video_url && (
                  <video
                    src={form.hero_video_url}
                    className="w-full h-20 object-cover rounded border border-border"
                    muted
                    playsInline
                  />
                )}
                <label className="flex items-center gap-2 cursor-pointer text-sm text-primary hover:underline">
                  <Upload className="w-4 h-4" />
                  {uploading ? "Uploading..." : "Upload Video"}
                  <input type="file" accept="video/*" className="hidden" onChange={handleVideoUpload} disabled={uploading} />
                </label>
                <p className="text-xs text-muted-foreground">Or paste a URL (YouTube embed, direct .mp4, etc.)</p>
                <div className="flex gap-2">
                  <Input
                    value={videoUrlInput}
                    onChange={(e) => setVideoUrlInput(e.target.value)}
                    placeholder="https://..."
                    className="text-sm"
                  />
                  <Button type="button" variant="outline" size="sm" onClick={handleVideoUrlSave}>
                    Save URL
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Contact Details */}
        <div className="border-t border-border pt-5 mt-2">
          <h3 className="text-sm font-semibold text-foreground mb-3">Contact Details (shown on tenant contact page)</h3>
          <div className="grid sm:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Contact Email</Label>
              <p className="text-xs text-muted-foreground">Form submissions will be sent to this address.</p>
              <Input
                type="email"
                value={form.contact_email}
                onChange={(e) => setForm(f => ({ ...f, contact_email: e.target.value }))}
                placeholder="bookings@company.com"
              />
            </div>
            <div className="space-y-2">
              <Label>Contact Phone</Label>
              <Input
                value={form.contact_phone}
                onChange={(e) => setForm(f => ({ ...f, contact_phone: e.target.value }))}
                placeholder="+44 123 456 789"
              />
            </div>
            <div className="space-y-2">
              <Label>Address</Label>
              <Input
                value={form.contact_address}
                onChange={(e) => setForm(f => ({ ...f, contact_address: e.target.value }))}
                placeholder="123 Training Lane, London"
              />
            </div>
            <div className="space-y-2">
              <Label>Opening Hours</Label>
              <Input
                value={form.opening_hours}
                onChange={(e) => setForm(f => ({ ...f, opening_hours: e.target.value }))}
                placeholder="Mon-Fri 8am-6pm"
              />
            </div>
          </div>
        </div>

        {/* Stripe Configuration */}
        <div className="border-t border-border pt-5 mt-2">
          <h3 className="text-sm font-semibold text-foreground mb-3">Stripe Payment Configuration</h3>
          <p className="text-xs text-muted-foreground mb-4">
            Enter the Stripe API keys for this company. Customers booking through their white-label site will pay via these keys.
          </p>
          <div className="grid sm:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Publishable Key</Label>
              <Input
                value={stripePublishableKey}
                onChange={(e) => setStripePublishableKey(e.target.value)}
                placeholder="pk_live_..."
                type="text"
              />
            </div>
            <div className="space-y-2">
              <Label>Secret Key</Label>
              <Input
                value={stripeSecretKey}
                onChange={(e) => setStripeSecretKey(e.target.value)}
                placeholder="sk_live_..."
                type="password"
              />
            </div>
          </div>
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="mt-3"
            disabled={savingStripe || !stripePublishableKey.trim() || !stripeSecretKey.trim()}
            onClick={handleSaveStripeConfig}
          >
            {savingStripe ? "Saving..." : stripeConfig ? "Update Stripe Keys" : "Save Stripe Keys"}
          </Button>
          {stripeConfig && (
            <p className="text-xs text-green-600 mt-2">✓ Stripe keys configured</p>
          )}
        </div>


        <div className="flex items-center gap-3">
          <Switch
            checked={form.is_active}
            onCheckedChange={(v) => setForm(f => ({ ...f, is_active: v }))}
          />
          <Label>Enable subdomain</Label>
        </div>

        {/* Tenant preview link */}
        {branding?.subdomain && (
          <div className="rounded-lg border border-border bg-muted/40 px-4 py-3 flex items-center justify-between gap-3">
            <div>
              <p className="text-xs font-medium text-muted-foreground mb-0.5">Tenant Preview URL</p>
              <p className="text-sm font-mono text-foreground">
                ?tenant={branding.subdomain}
              </p>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <a
                href={`https://utc-prototype.lovable.app/?tenant=${branding.subdomain}`}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1.5 text-sm text-primary hover:underline"
              >
                <ExternalLink className="w-3.5 h-3.5" />
                Open Preview
              </a>
            </div>
          </div>
        )}

        <div className="flex items-center gap-3">
          <Button type="submit" variant="hero" disabled={upsertMutation.isPending}>
            {upsertMutation.isPending ? "Saving..." : "Save Branding"}
          </Button>
          <div className="flex items-center gap-2">
            <Switch
              checked={form.is_active}
              onCheckedChange={(v) => setForm(f => ({ ...f, is_active: v }))}
            />
            <Label>Enable subdomain</Label>
          </div>
        </div>
      </form>
    </div>
  );
};

export default CompanyBrandingPanel;
