'use client';

import { useState, useEffect, useRef } from 'react';
import { Loader2, Save, Image, Palette, Type, Upload, X, Monitor, FileText } from 'lucide-react';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { useBranding } from '@client/contexts/BrandingContext';

interface BrandingData {
  site_logo_url: string;
  site_favicon_url: string;
  site_primary_color: string;
  site_font_family: string;
  site_title: string;
  site_tagline: string;
}

const FONT_OPTIONS = [
  { label: 'Inter (default)', value: 'Inter' },
  { label: 'Poppins', value: 'Poppins' },
  { label: 'Roboto', value: 'Roboto' },
  { label: 'DM Sans', value: 'DM Sans' },
  { label: 'Plus Jakarta Sans', value: 'Plus Jakarta Sans' },
  { label: 'Nunito', value: 'Nunito' },
  { label: 'Lato', value: 'Lato' },
  { label: 'Montserrat', value: 'Montserrat' },
];

const COLOR_PRESETS = [
  { label: 'Orange', value: '#f97316' },
  { label: 'Sky', value: '#0ea5e9' },
  { label: 'Violet', value: '#8b5cf6' },
  { label: 'Emerald', value: '#10b981' },
  { label: 'Red', value: '#ef4444' },
  { label: 'Amber', value: '#f59e0b' },
  { label: 'Indigo', value: '#6366f1' },
  { label: 'Pink', value: '#ec4899' },
  { label: 'Teal', value: '#14b8a6' },
  { label: 'Slate', value: '#64748b' },
];

const DEFAULT_BRANDING: BrandingData = {
  site_logo_url: '',
  site_favicon_url: '',
  site_primary_color: '#f97316',
  site_font_family: 'Inter',
  site_title: 'RestroAgent',
  site_tagline: 'AI-powered restaurant management, simplified.',
};

function SectionHeader({ icon, title, description }: { icon: React.ReactNode; title: string; description: string }) {
  return (
    <div className="flex items-center gap-3 mb-5">
      <div className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
        {icon}
      </div>
      <div>
        <p className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{title}</p>
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{description}</p>
      </div>
    </div>
  );
}

function ImageField({
  label,
  hint,
  value,
  uploadType,
  onChange,
  t,
  showPreview = false,
}: {
  label: string;
  hint: string;
  value: string;
  uploadType: 'logo' | 'favicon';
  onChange: (url: string) => void;
  t: (key: string, fallback: string) => string;
  showPreview?: boolean;
}) {
  const fileRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append('type', uploadType);
      fd.append('file', file);
      const res = await fetch('/api/admin/branding-upload', { method: 'POST', body: fd });
      const data = await res.json() as { url?: string; error?: string };
      if (!res.ok) throw new Error(data.error || t('admin.branding.uploadFailed', 'Upload failed'));
      onChange(data.url!);
      toast.success(t('admin.branding.uploaded', '{label} uploaded').replace('{label}', label));
    } catch (err: any) {
      toast.error(err.message || t('admin.branding.uploadFailed', 'Upload failed'));
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = '';
    }
  }

  return (
    <div>
      <p className="text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{label}</p>
      <p className="text-xs mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{hint}</p>
      <div className="flex gap-2">
        <input
          type="url"
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder={t('admin.branding.imageUrlPlaceholder', 'https://example.com/image.png')}
          className="flex-1 min-w-0 px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
          style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
        />
        <button
          type="button"
          onClick={() => fileRef.current?.click()}
          disabled={uploading}
          className="flex items-center gap-1.5 px-3 py-2.5 rounded-xl text-xs font-semibold shrink-0 transition-all hover:-translate-y-0.5 disabled:opacity-60"
          style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
        >
          {uploading ? <Loader2 size={13} className="animate-spin" /> : <Upload size={13} />}
          {uploading ? t('admin.branding.uploading', 'Uploading…') : t('admin.branding.upload', 'Upload')}
        </button>
        <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleFile} />
      </div>
      {value && showPreview && (
        <div className="mt-3 flex items-center gap-3 p-3 rounded-xl" style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))' }}>
          <img
            src={value}
            alt={`${label} preview`}
            className="h-10 max-w-[140px] object-contain rounded"
            onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }}
          />
          <div className="flex-1 min-w-0">
            <p className="text-xs font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.branding.preview', 'Preview')}</p>
            <p className="text-xs truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>{value}</p>
          </div>
          <button
            type="button"
            onClick={() => onChange('')}
            className="shrink-0 p-1 rounded-lg hover:bg-black/5 transition-colors"
            title={t('admin.branding.remove', 'Remove')}
          >
            <X size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
          </button>
        </div>
      )}
      {value && !showPreview && (
        <div className="mt-2 flex items-center gap-2">
          <p className="text-xs truncate flex-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{value}</p>
          <button type="button" onClick={() => onChange('')} className="shrink-0" title={t('admin.branding.remove', 'Remove')}>
            <X size={13} style={{ color: 'hsl(var(--muted-foreground))' }} />
          </button>
        </div>
      )}
    </div>
  );
}

export default function AdminBrandingPage() {
  const { t } = useLanguage();
  const { refreshBranding } = useBranding();
  usePageHeader(t('admin.branding.pageTitle', 'Branding'), t('admin.branding.pageDescription', 'Customize platform identity, colors, and typography'));

  const [branding, setBranding] = useState<BrandingData>(DEFAULT_BRANDING);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const colorInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => { fetchBranding(); }, []);

  async function fetchBranding() {
    setLoading(true);
    try {
      const res = await fetch('/api/admin/branding');
      if (res.ok) {
        const data = await res.json() as { branding: Partial<BrandingData> };
        setBranding(prev => ({ ...prev, ...data.branding }));
      }
    } catch {
      toast.error(t('admin.branding.failedToLoad', 'Failed to load branding settings'));
    } finally {
      setLoading(false);
    }
  }

  async function handleSave() {
    setSaving(true);
    try {
      const res = await fetch('/api/admin/branding', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(branding),
      });
      if (res.ok) {
        toast.success(t('admin.branding.saved', 'Branding settings saved'));
        void refreshBranding();
      } else {
        const data = await res.json() as { error?: string };
        toast.error(data.error || t('admin.branding.failedToSave', 'Failed to save branding'));
      }
    } catch {
      toast.error(t('admin.branding.failedToSave', 'Failed to save branding settings'));
    } finally {
      setSaving(false);
    }
  }

  function set(key: keyof BrandingData, value: string) {
    setBranding(prev => ({ ...prev, [key]: value }));
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 size={24} className="animate-spin" style={{ color: 'hsl(var(--muted-foreground))' }} />
      </div>
    );
  }

  const tabPreview = [branding.site_tagline, branding.site_title].filter(Boolean).join(' — ') || 'RestroAgent';

  return (
    <div className="max-w-2xl mx-auto px-4 py-6 space-y-6">

      {/* ── Identity ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Image size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.branding.identity', 'Identity')}
          description={t('admin.branding.identityDescription', 'Logo and favicon shown across the platform and public pages')}
        />
        <div className="space-y-5">
          <ImageField
            label={t('admin.branding.platformLogo', 'Platform Logo')}
            hint={t('admin.branding.platformLogoHint', 'Shown in the navbar, login page, and sidebar. SVG or PNG recommended.')}
            value={branding.site_logo_url}
            uploadType="logo"
            onChange={v => set('site_logo_url', v)}
            t={t}
            showPreview
          />
          <div className="border-t" style={{ borderColor: 'hsl(var(--border))' }} />
          <ImageField
            label={t('admin.branding.favicon', 'Favicon')}
            hint={t('admin.branding.faviconHint', 'Browser tab icon. PNG 32×32 or WEBP recommended. Provide a URL for ICO/SVG.')}
            value={branding.site_favicon_url}
            uploadType="favicon"
            onChange={v => set('site_favicon_url', v)}
            t={t}
            showPreview={false}
          />
        </div>
      </div>

      {/* ── Site Info ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Monitor size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.branding.siteInfo', 'Site Info')}
          description={t('admin.branding.siteInfoDescription', 'Title and tagline shown in browser tabs and public pages')}
        />
        <div className="space-y-4">
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.branding.siteTitle', 'Site Title')}</label>
            <input
              type="text"
              value={branding.site_title}
              onChange={e => set('site_title', e.target.value)}
              placeholder={t('admin.branding.siteTitlePlaceholder', 'RestroAgent')}
              maxLength={60}
              className="w-full px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
              style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
            />
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.branding.tagline', 'Tagline')}</label>
            <input
              type="text"
              value={branding.site_tagline}
              onChange={e => set('site_tagline', e.target.value)}
              placeholder={t('admin.branding.taglinePlaceholder', 'AI-powered restaurant management, simplified.')}
              maxLength={120}
              className="w-full px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
              style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
            />
          </div>
          <div className="flex items-center gap-2 px-3 py-2 rounded-xl" style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))' }}>
            <FileText size={13} style={{ color: 'hsl(var(--muted-foreground))' }} />
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('admin.branding.browserTabPreview', 'Browser tab preview')}: <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{tabPreview}</span>
            </p>
          </div>
        </div>
      </div>

      {/* ── Appearance ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Palette size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.branding.appearance', 'Appearance')}
          description={t('admin.branding.appearanceDescription', 'Primary brand color used across landing pages, buttons, and accents')}
        />
        <div className="flex items-center gap-3 mb-3">
          <button
            type="button"
            onClick={() => colorInputRef.current?.click()}
            className="w-11 h-11 rounded-xl border-2 flex-shrink-0 transition-transform hover:scale-105 shadow-sm"
            style={{ backgroundColor: branding.site_primary_color, borderColor: 'hsl(var(--border))' }}
            title={t('admin.branding.openColorPicker', 'Open color picker')}
          />
          <input
            ref={colorInputRef}
            type="color"
            value={branding.site_primary_color}
            onChange={e => set('site_primary_color', e.target.value)}
            className="sr-only"
          />
          <input
            type="text"
            value={branding.site_primary_color}
            onChange={e => set('site_primary_color', e.target.value)}
            placeholder="#f97316"
            maxLength={7}
            className="flex-1 px-3 py-2.5 rounded-xl text-sm font-mono transition-all duration-200"
            style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
          />
        </div>
        <div className="flex flex-wrap gap-2">
          {COLOR_PRESETS.map(({ label, value }) => (
            <button
              key={value}
              type="button"
              onClick={() => set('site_primary_color', value)}
              className="w-7 h-7 rounded-lg border-2 transition-all hover:scale-110"
              style={{
                backgroundColor: value,
                borderColor: branding.site_primary_color === value ? 'hsl(var(--foreground))' : 'transparent',
                boxShadow: branding.site_primary_color === value ? '0 0 0 2px white, 0 0 0 3px ' + value : undefined,
              }}
              title={label}
            />
          ))}
        </div>
      </div>

      {/* ── Typography ── */}
      <div className="p-6 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <SectionHeader
          icon={<Type size={16} style={{ color: 'hsl(var(--primary))' }} />}
          title={t('admin.branding.typography', 'Typography')}
          description={t('admin.branding.typographyDescription', 'Primary typeface applied to the landing pages and public-facing UI')}
        />
        <select
          value={branding.site_font_family}
          onChange={e => set('site_font_family', e.target.value)}
          className="w-full px-3 py-2.5 rounded-xl text-sm transition-all duration-200"
          style={{ backgroundColor: 'hsl(var(--background))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
        >
          {FONT_OPTIONS.map(f => (
            <option key={f.value} value={f.value}>{f.label}</option>
          ))}
        </select>
        <p className="mt-3 text-sm px-1" style={{ fontFamily: branding.site_font_family, color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.branding.typographyPreview', 'Preview: The quick brown fox jumps over the lazy dog.')}
        </p>
      </div>

      {/* ── Save ── */}
      <div className="flex items-center justify-between pt-1">
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('admin.branding.saveNotice', 'Changes apply to public-facing pages after save.')}
        </p>
        <button
          onClick={handleSave}
          disabled={saving}
          className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold transition-all duration-200 hover:-translate-y-0.5 disabled:opacity-60 disabled:cursor-not-allowed"
          style={{ backgroundColor: 'hsl(var(--primary))', color: 'white' }}
        >
          {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
          {saving ? t('admin.branding.saving', 'Saving…') : t('admin.branding.saveBranding', 'Save Branding')}
        </button>
      </div>
    </div>
  );
}
