"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { ImageUp } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Card, Button, Input, Textarea, FormField, Skeleton } from "@/components/ui";
import { SettingsTabs } from "@/components/settings-tabs";
import { useToast } from "@/components/toast";

type Branding = {
  logoUrl: string | null;
  brandColor: string | null;
  brandSecondaryColor: string | null;
  portalSubdomain: string | null;
  termsText: string | null;
};

export default function BrandingPage() {
  const toast = useToast();
  const [form, setForm] = useState<Branding | null>(null);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    api.get("/admin/branding").then(setForm);
  }, []);

  const set = (k: keyof Branding, v: string) => setForm((f) => (f ? { ...f, [k]: v } : f));

  const onPickLogo = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.type.startsWith("image/")) {
      toast.error("Please choose an image file.");
      return;
    }
    if (file.size > 500 * 1024) {
      toast.error("Image too large — please use one under 500 KB.");
      return;
    }
    const reader = new FileReader();
    reader.onload = () => set("logoUrl", String(reader.result));
    reader.readAsDataURL(file);
  };

  const save = async () => {
    if (!form) return;
    setSaving(true);
    try {
      await api.put("/admin/branding", form);
      toast.success("Branding saved.");
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  if (!form) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-8 w-40" />
        <Skeleton className="h-56" />
      </div>
    );
  }

  const primary = form.brandColor || "#1A3C6E";
  const secondary = form.brandSecondaryColor || "#EAF2FB";

  return (
    <div>
      <PageHeader title="Settings" subtitle="Affiliate portal look & feel" actions={<Button onClick={save} loading={saving}>Save branding</Button>} />
      <SettingsTabs />

      <div className="grid gap-4 lg:grid-cols-3">
        <div className="space-y-4 lg:col-span-2">
          <Card title="Logo & portal">
            <FormField label="Logo" hint="Upload an image or paste a URL — shown in the sidebar & emails">
              <div className="flex items-center gap-3">
                {form.logoUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={form.logoUrl} alt="logo" className="h-12 w-12 shrink-0 rounded-lg border border-gray-200 object-contain p-1" />
                ) : (
                  <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg border border-dashed border-gray-300 text-xs text-gray-400">Logo</span>
                )}
                <div className="flex flex-col gap-2">
                  <label className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg border border-gray-300 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">
                    <ImageUp className="h-3.5 w-3.5" /> Choose image
                    <input type="file" accept="image/*" className="hidden" onChange={onPickLogo} />
                  </label>
                  {form.logoUrl && (
                    <button onClick={() => set("logoUrl", "")} className="text-left text-xs text-red-600 hover:underline">Remove logo</button>
                  )}
                </div>
              </div>
            </FormField>
            <div className="mt-4">
              <FormField label="…or paste a logo URL">
                <Input value={form.logoUrl?.startsWith("data:") ? "" : form.logoUrl ?? ""} onChange={(e) => set("logoUrl", e.target.value)} placeholder="https://…/logo.png" />
              </FormField>
            </div>
            <div className="mt-4">
              <FormField label="Custom portal subdomain" hint="Where affiliates access their portal">
                <Input value={form.portalSubdomain ?? ""} onChange={(e) => set("portalSubdomain", e.target.value)} placeholder="partners.caffeine.in" />
              </FormField>
            </div>
          </Card>

          <Card title="Brand colors">
            <div className="grid gap-4 sm:grid-cols-2">
              <FormField label="Primary color">
                <div className="flex items-center gap-2">
                  <input type="color" value={primary} onChange={(e) => set("brandColor", e.target.value)} className="h-10 w-12 shrink-0 cursor-pointer rounded-lg border border-gray-300" />
                  <Input value={form.brandColor ?? ""} onChange={(e) => set("brandColor", e.target.value)} placeholder="#1A3C6E" className="font-mono" />
                </div>
              </FormField>
              <FormField label="Secondary color">
                <div className="flex items-center gap-2">
                  <input type="color" value={secondary} onChange={(e) => set("brandSecondaryColor", e.target.value)} className="h-10 w-12 shrink-0 cursor-pointer rounded-lg border border-gray-300" />
                  <Input value={form.brandSecondaryColor ?? ""} onChange={(e) => set("brandSecondaryColor", e.target.value)} placeholder="#EAF2FB" className="font-mono" />
                </div>
              </FormField>
            </div>
          </Card>

          <Card title="Terms & Conditions" subtitle="Shown to affiliates during signup">
            <FormField>
              <Textarea rows={5} value={form.termsText ?? ""} onChange={(e) => set("termsText", e.target.value)} placeholder="Affiliates must agree to these terms…" />
            </FormField>
          </Card>
        </div>

        {/* Live preview */}
        <div>
          <Card title="Preview">
            <div className="overflow-hidden rounded-xl border border-gray-200">
              <div className="flex items-center gap-2 px-4 py-3" style={{ backgroundColor: primary }}>
                {form.logoUrl ? (
                  <Image src={form.logoUrl} alt="logo" width={24} height={24} className="h-6 w-6 rounded object-contain" unoptimized />
                ) : (
                  <span className="flex h-6 w-6 items-center justify-center rounded bg-white/20 text-xs font-bold text-white">PN</span>
                )}
                <span className="text-sm font-semibold text-white">Partner portal</span>
              </div>
              <div className="space-y-3 p-4" style={{ backgroundColor: secondary }}>
                <div className="rounded-lg bg-white p-3 shadow-sm">
                  <p className="text-xs text-gray-400">Your referral link</p>
                  <p className="truncate text-sm font-medium text-gray-800">partners.example/r/SARA10</p>
                </div>
                <button className="w-full rounded-lg py-2 text-sm font-medium text-white" style={{ backgroundColor: primary }}>
                  Request payout
                </button>
              </div>
            </div>
            <p className="mt-3 text-xs text-gray-400">This is how your colors will appear to affiliates.</p>
          </Card>
        </div>
      </div>
    </div>
  );
}
