import { useState, useEffect, useRef } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../api/client';

interface BrandingData {
  logo: string | null;
  sidebarColor: string | null;
  logoWidth: number | null;
  sidebarWidth: number | null;
  loginBgType: 'gradient' | 'solid' | 'image' | null;
  loginBgColor1: string | null;
  loginBgColor2: string | null;
  loginBgImage: string | null;
}

const SIDEBAR_PRESETS = [
  { label: 'Standard', color: '#1e293b' },
  { label: 'Dunkelblau', color: '#0f172a' },
  { label: 'Marine', color: '#1e3a5f' },
  { label: 'Anthrazit', color: '#18181b' },
  { label: 'Dunkelgrau', color: '#374151' },
  { label: 'Schwarz', color: '#0a0a0a' },
  { label: 'Dunkelgruen', color: '#14532d' },
  { label: 'Bordeaux', color: '#4a1d2e' },
];

const cardStyle: React.CSSProperties = {
  background: 'var(--color-bg-card)',
  borderRadius: 'var(--radius-md)',
  boxShadow: 'var(--shadow-sm)',
  border: '1px solid var(--color-border)',
  padding: '1.5rem',
  marginBottom: '1.5rem',
};

const btnPrimary: React.CSSProperties = {
  padding: '0.5rem 1.25rem',
  background: 'var(--color-primary)',
  color: 'white',
  border: 'none',
  borderRadius: 'var(--radius-sm)',
  fontSize: '0.875rem',
  fontWeight: 600,
  cursor: 'pointer',
};

const btnSecondary: React.CSSProperties = {
  padding: '0.375rem 0.75rem',
  background: 'none',
  color: 'var(--color-text-secondary)',
  border: '1px solid var(--color-border)',
  borderRadius: 'var(--radius-sm)',
  fontSize: '0.8125rem',
  cursor: 'pointer',
};

const labelStyle: React.CSSProperties = {
  display: 'block',
  fontSize: '0.75rem',
  fontWeight: 600,
  color: 'var(--color-text-secondary)',
  marginBottom: '0.25rem',
  textTransform: 'uppercase' as const,
  letterSpacing: '0.5px',
};

export function AdminCustomizePage() {
  const queryClient = useQueryClient();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const loginBgFileInputRef = useRef<HTMLInputElement>(null);
  const [logo, setLogo] = useState<string | null>(null);
  const [sidebarColor, setSidebarColor] = useState<string>('#1e293b');
  const [logoWidth, setLogoWidth] = useState<number>(160);
  const [sidebarWidth, setSidebarWidth] = useState<number>(240);
  const [loginBgType, setLoginBgType] = useState<'gradient' | 'solid' | 'image'>('gradient');
  const [loginBgColor1, setLoginBgColor1] = useState<string>('#1a56db');
  const [loginBgColor2, setLoginBgColor2] = useState<string>('#1e3a5f');
  const [loginBgImage, setLoginBgImage] = useState<string | null>(null);
  const [hasChanges, setHasChanges] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);

  const { data } = useQuery<BrandingData>({
    queryKey: ['settings', 'branding'],
    queryFn: async () => {
      const res = await api.get<BrandingData>('/settings/branding');
      return res.data;
    },
  });

  useEffect(() => {
    if (data) {
      setLogo(data.logo);
      setSidebarColor(data.sidebarColor || '#1e293b');
      setLogoWidth(data.logoWidth ?? 160);
      setSidebarWidth(data.sidebarWidth ?? 240);
      setLoginBgType(data.loginBgType || 'gradient');
      setLoginBgColor1(data.loginBgColor1 || '#1a56db');
      setLoginBgColor2(data.loginBgColor2 || '#1e3a5f');
      setLoginBgImage(data.loginBgImage || null);
      setHasChanges(false);
    }
  }, [data]);

  const saveMutation = useMutation({
    mutationFn: async (branding: {
      logo: string | null;
      sidebarColor: string;
      logoWidth: number;
      sidebarWidth: number;
      loginBgType: string;
      loginBgColor1: string;
      loginBgColor2: string;
      loginBgImage: string | null;
    }) => {
      const res = await api.post('/settings/branding', branding);
      return res.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings', 'branding'] });
      setHasChanges(false);
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    },
  });

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      alert('Bitte nur Bilddateien hochladen');
      return;
    }

    if (file.size > 500_000) {
      alert('Datei darf maximal 500KB gross sein');
      return;
    }

    const reader = new FileReader();
    reader.onload = () => {
      setLogo(reader.result as string);
      setHasChanges(true);
    };
    reader.readAsDataURL(file);
  };

  const handleRemoveLogo = () => {
    setLogo(null);
    setHasChanges(true);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleSave = () => {
    saveMutation.mutate({ logo, sidebarColor, logoWidth, sidebarWidth, loginBgType, loginBgColor1, loginBgColor2, loginBgImage });
  };

  const handleLoginBgFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      alert('Bitte nur Bilddateien hochladen');
      return;
    }

    if (file.size > 2_000_000) {
      alert('Datei darf maximal 2MB gross sein');
      return;
    }

    const reader = new FileReader();
    reader.onload = () => {
      setLoginBgImage(reader.result as string);
      setHasChanges(true);
    };
    reader.readAsDataURL(file);
  };

  const loginBgPreviewStyle: React.CSSProperties = (() => {
    if (loginBgType === 'gradient') {
      return { background: `linear-gradient(135deg, ${loginBgColor1} 0%, ${loginBgColor2} 100%)` };
    }
    if (loginBgType === 'solid') {
      return { background: loginBgColor1 };
    }
    if (loginBgType === 'image' && loginBgImage) {
      return { background: `url(${loginBgImage}) center/cover no-repeat` };
    }
    return { background: `linear-gradient(135deg, ${loginBgColor1} 0%, ${loginBgColor2} 100%)` };
  })();

  return (
    <div>
      <div style={{ marginBottom: '1.5rem' }}>
        <h1 style={{ fontSize: '1.5rem', fontWeight: 600 }}>Anpassungen</h1>
        <p
          style={{
            fontSize: '0.875rem',
            color: 'var(--color-text-secondary)',
            marginTop: '0.25rem',
          }}
        >
          Logo, Farben und Branding-Einstellungen fuer die Plattform.
        </p>
      </div>

      {/* Logo */}
      <div style={cardStyle}>
        <h3
          style={{
            fontSize: '1rem',
            fontWeight: 600,
            marginBottom: '1rem',
          }}
        >
          Plattform-Logo
        </h3>
        <p
          style={{
            fontSize: '0.8125rem',
            color: 'var(--color-text-secondary)',
            marginBottom: '1rem',
          }}
        >
          Das Logo wird oben links in der Sidebar angezeigt. Empfohlen: PNG oder
          SVG mit transparentem Hintergrund, max. 500KB.
        </p>

        {/* Vorschau + Upload */}
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: '1.5rem',
            marginBottom: '1.25rem',
          }}
        >
          <div
            style={{
              width: 120,
              height: 60,
              borderRadius: 'var(--radius-sm)',
              border: '2px dashed var(--color-border)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              overflow: 'hidden',
              background: sidebarColor,
              flexShrink: 0,
            }}
          >
            {logo ? (
              <img
                src={logo}
                alt="Logo"
                style={{
                  maxWidth: `${Math.round(logoWidth * 0.72)}px`,
                  maxHeight: '100%',
                  objectFit: 'contain',
                }}
              />
            ) : (
              <span
                style={{
                  color: '#60a5fa',
                  fontWeight: 700,
                  letterSpacing: 2,
                  fontSize: '1.25rem',
                }}
              >
                INSIGHT
              </span>
            )}
          </div>

          <div style={{ display: 'flex', gap: '0.5rem' }}>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              style={{ display: 'none' }}
              onChange={handleFileSelect}
            />
            <button
              style={btnSecondary}
              onClick={() => fileInputRef.current?.click()}
            >
              Logo hochladen
            </button>
            {logo && (
              <button
                style={{
                  ...btnSecondary,
                  color: 'var(--color-error)',
                  borderColor: 'var(--color-error)',
                }}
                onClick={handleRemoveLogo}
              >
                Entfernen
              </button>
            )}
          </div>
        </div>

        {/* Logo-Breite Slider */}
        <div>
          <label style={labelStyle}>
            Logo-Breite: <strong>{logoWidth}px</strong>
          </label>
          <input
            type="range"
            min={40}
            max={240}
            step={10}
            value={logoWidth}
            onChange={(e) => {
              setLogoWidth(Number(e.target.value));
              setHasChanges(true);
            }}
            style={{ width: '100%', maxWidth: 320, display: 'block', marginBottom: '0.25rem' }}
          />
          <div style={{ display: 'flex', justifyContent: 'space-between', maxWidth: 320, fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>
            <span>40px</span>
            <span>240px</span>
          </div>
        </div>
      </div>

      {/* Sidebar-Farbe */}
      <div style={cardStyle}>
        <h3
          style={{
            fontSize: '1rem',
            fontWeight: 600,
            marginBottom: '1rem',
          }}
        >
          Sidebar-Farbe
        </h3>
        <p
          style={{
            fontSize: '0.8125rem',
            color: 'var(--color-text-secondary)',
            marginBottom: '1rem',
          }}
        >
          Die Hintergrundfarbe der linken Menue-Leiste.
        </p>

        {/* Voreinstellungen */}
        <div style={{ marginBottom: '1rem' }}>
          <label style={labelStyle}>Voreinstellungen</label>
          <div
            style={{
              display: 'flex',
              flexWrap: 'wrap',
              gap: '0.5rem',
            }}
          >
            {SIDEBAR_PRESETS.map((preset) => (
              <button
                key={preset.color}
                onClick={() => {
                  setSidebarColor(preset.color);
                  setHasChanges(true);
                }}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.5rem',
                  padding: '0.375rem 0.75rem',
                  background:
                    sidebarColor === preset.color
                      ? 'var(--color-primary-light)'
                      : 'none',
                  border:
                    sidebarColor === preset.color
                      ? '2px solid var(--color-primary)'
                      : '1px solid var(--color-border)',
                  borderRadius: 'var(--radius-sm)',
                  cursor: 'pointer',
                  fontSize: '0.8125rem',
                  color: 'var(--color-text)',
                }}
              >
                <span
                  style={{
                    width: 20,
                    height: 20,
                    borderRadius: 3,
                    background: preset.color,
                    border: '1px solid rgba(0,0,0,0.2)',
                    flexShrink: 0,
                  }}
                />
                {preset.label}
              </button>
            ))}
          </div>
        </div>

        {/* Eigene Farbe */}
        <div>
          <label style={labelStyle}>Eigene Farbe</label>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '0.75rem',
            }}
          >
            <input
              type="color"
              value={sidebarColor}
              onChange={(e) => {
                setSidebarColor(e.target.value);
                setHasChanges(true);
              }}
              style={{
                width: 40,
                height: 40,
                padding: 0,
                border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-sm)',
                cursor: 'pointer',
              }}
            />
            <input
              type="text"
              value={sidebarColor}
              onChange={(e) => {
                setSidebarColor(e.target.value);
                setHasChanges(true);
              }}
              style={{
                padding: '0.5rem 0.75rem',
                fontSize: '0.875rem',
                border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-sm)',
                background: 'var(--color-bg-card)',
                color: 'var(--color-text)',
                width: 120,
                fontFamily: 'monospace',
              }}
            />
            {/* Live-Vorschau */}
            <div
              style={{
                width: 160,
                height: 80,
                borderRadius: 'var(--radius-sm)',
                background: sidebarColor,
                border: '1px solid var(--color-border)',
                display: 'flex',
                flexDirection: 'column',
                padding: '0.5rem',
                gap: '0.25rem',
              }}
            >
              <div
                style={{
                  fontSize: '0.5rem',
                  color: '#60a5fa',
                  fontWeight: 700,
                  letterSpacing: 1,
                }}
              >
                INSIGHT
              </div>
              <div
                style={{
                  height: 4,
                  width: '60%',
                  background: 'rgba(255,255,255,0.2)',
                  borderRadius: 2,
                }}
              />
              <div
                style={{
                  height: 4,
                  width: '80%',
                  background: 'rgba(255,255,255,0.15)',
                  borderRadius: 2,
                }}
              />
              <div
                style={{
                  height: 4,
                  width: '50%',
                  background: 'rgba(255,255,255,0.1)',
                  borderRadius: 2,
                }}
              />
            </div>
          </div>
        </div>
      </div>

      {/* Sidebar-Breite */}
      <div style={cardStyle}>
        <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '1rem' }}>
          Sidebar-Breite
        </h3>
        <p style={{ fontSize: '0.8125rem', color: 'var(--color-text-secondary)', marginBottom: '1rem' }}>
          Breite der linken Menü-Leiste im ausgeklappten Zustand.
        </p>

        {/* Slider + Vorschau */}
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: '2rem', flexWrap: 'wrap' }}>
          <div style={{ flex: '1 1 280px' }}>
            <label style={labelStyle}>
              Breite: <strong>{sidebarWidth}px</strong>
            </label>
            <input
              type="range"
              min={200}
              max={360}
              step={10}
              value={sidebarWidth}
              onChange={(e) => {
                setSidebarWidth(Number(e.target.value));
                setHasChanges(true);
              }}
              style={{ width: '100%', maxWidth: 320, display: 'block', marginBottom: '0.25rem' }}
            />
            <div style={{ display: 'flex', justifyContent: 'space-between', maxWidth: 320, fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>
              <span>200px (schmal)</span>
              <span>360px (breit)</span>
            </div>
          </div>

          {/* Sidebar-Vorschau skaliert */}
          <div
            style={{
              width: Math.round(sidebarWidth * 0.45),
              height: 100,
              borderRadius: 'var(--radius-sm)',
              background: sidebarColor,
              border: '1px solid var(--color-border)',
              display: 'flex',
              flexDirection: 'column',
              padding: '0.5rem 0.625rem',
              gap: '0.35rem',
              overflow: 'hidden',
              flexShrink: 0,
              transition: 'width 0.15s',
            }}
          >
            {/* Mini-Logo */}
            <div style={{ fontSize: '0.5rem', color: '#60a5fa', fontWeight: 700, letterSpacing: 1, marginBottom: '0.25rem' }}>
              {logo ? (
                <img src={logo} alt="" style={{ maxWidth: Math.round(logoWidth * 0.3), maxHeight: 12, objectFit: 'contain' }} />
              ) : 'INSIGHT'}
            </div>
            {/* Mini Nav-Einträge */}
            {[80, 65, 75, 55].map((w, i) => (
              <div key={i} style={{ height: 5, width: `${w}%`, background: 'rgba(255,255,255,0.2)', borderRadius: 2 }} />
            ))}
          </div>
        </div>
      </div>

      {/* Login-Hintergrund */}
      <div style={cardStyle}>
        <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '0.5rem' }}>
          Login-Hintergrund
        </h3>
        <p style={{ fontSize: '0.8125rem', color: 'var(--color-text-secondary)', marginBottom: '1.25rem' }}>
          Hintergrund des Login-Screens. Das Plattform-Logo (oben) wird ebenfalls auf dem Login-Screen angezeigt.
        </p>

        {/* Typ-Toggle */}
        <div style={{ marginBottom: '1.25rem' }}>
          <label style={labelStyle}>Hintergrundtyp</label>
          <div style={{ display: 'flex', gap: '0.5rem' }}>
            {(['gradient', 'solid', 'image'] as const).map((type) => (
              <button
                key={type}
                onClick={() => { setLoginBgType(type); setHasChanges(true); }}
                style={{
                  padding: '0.375rem 0.875rem',
                  fontSize: '0.8125rem',
                  border: loginBgType === type ? '2px solid var(--color-primary)' : '1px solid var(--color-border)',
                  borderRadius: 'var(--radius-sm)',
                  background: loginBgType === type ? 'var(--color-primary-light)' : 'none',
                  color: 'var(--color-text)',
                  cursor: 'pointer',
                  fontWeight: loginBgType === type ? 600 : 400,
                }}
              >
                {type === 'gradient' ? 'Farbverlauf' : type === 'solid' ? 'Einfarbig' : 'Hintergrundbild'}
              </button>
            ))}
          </div>
        </div>

        {/* Farbverlauf */}
        {loginBgType === 'gradient' && (
          <div style={{ display: 'flex', gap: '2rem', marginBottom: '1.25rem', flexWrap: 'wrap' }}>
            <div>
              <label style={labelStyle}>Von</label>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                <input
                  type="color"
                  value={loginBgColor1}
                  onChange={(e) => { setLoginBgColor1(e.target.value); setHasChanges(true); }}
                  style={{ width: 40, height: 36, padding: 0, border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', cursor: 'pointer' }}
                />
                <input
                  type="text"
                  value={loginBgColor1}
                  onChange={(e) => { setLoginBgColor1(e.target.value); setHasChanges(true); }}
                  style={{ padding: '0.375rem 0.5rem', fontSize: '0.875rem', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', background: 'var(--color-bg-card)', color: 'var(--color-text)', width: 100, fontFamily: 'monospace' }}
                />
              </div>
            </div>
            <div>
              <label style={labelStyle}>Bis</label>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                <input
                  type="color"
                  value={loginBgColor2}
                  onChange={(e) => { setLoginBgColor2(e.target.value); setHasChanges(true); }}
                  style={{ width: 40, height: 36, padding: 0, border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', cursor: 'pointer' }}
                />
                <input
                  type="text"
                  value={loginBgColor2}
                  onChange={(e) => { setLoginBgColor2(e.target.value); setHasChanges(true); }}
                  style={{ padding: '0.375rem 0.5rem', fontSize: '0.875rem', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', background: 'var(--color-bg-card)', color: 'var(--color-text)', width: 100, fontFamily: 'monospace' }}
                />
              </div>
            </div>
          </div>
        )}

        {/* Einfarbig */}
        {loginBgType === 'solid' && (
          <div style={{ marginBottom: '1.25rem' }}>
            <label style={labelStyle}>Farbe</label>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
              <input
                type="color"
                value={loginBgColor1}
                onChange={(e) => { setLoginBgColor1(e.target.value); setHasChanges(true); }}
                style={{ width: 40, height: 40, padding: 0, border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', cursor: 'pointer' }}
              />
              <input
                type="text"
                value={loginBgColor1}
                onChange={(e) => { setLoginBgColor1(e.target.value); setHasChanges(true); }}
                style={{ padding: '0.5rem 0.75rem', fontSize: '0.875rem', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', background: 'var(--color-bg-card)', color: 'var(--color-text)', width: 120, fontFamily: 'monospace' }}
              />
            </div>
          </div>
        )}

        {/* Hintergrundbild */}
        {loginBgType === 'image' && (
          <div style={{ marginBottom: '1.25rem' }}>
            <label style={labelStyle}>Hintergrundbild</label>
            <p style={{ fontSize: '0.8125rem', color: 'var(--color-text-secondary)', marginBottom: '0.75rem' }}>
              Empfohlen: JPG oder PNG, min. 1920×1080px, max. 2MB.
            </p>
            <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
              <input
                ref={loginBgFileInputRef}
                type="file"
                accept="image/*"
                style={{ display: 'none' }}
                onChange={handleLoginBgFileSelect}
              />
              <button style={btnSecondary} onClick={() => loginBgFileInputRef.current?.click()}>
                Bild hochladen
              </button>
              {loginBgImage && (
                <button
                  style={{ ...btnSecondary, color: 'var(--color-error)', borderColor: 'var(--color-error)' }}
                  onClick={() => { setLoginBgImage(null); setHasChanges(true); }}
                >
                  Entfernen
                </button>
              )}
              {loginBgImage && (
                <span style={{ fontSize: '0.8125rem', color: 'var(--color-success)' }}>✓ Bild geladen</span>
              )}
            </div>
          </div>
        )}

        {/* Vorschau */}
        <div>
          <label style={labelStyle}>Vorschau</label>
          <div
            style={{
              ...loginBgPreviewStyle,
              width: 200,
              height: 120,
              borderRadius: 'var(--radius-sm)',
              border: '1px solid var(--color-border)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            {/* Mini-Login-Card */}
            <div
              style={{
                width: 80,
                height: 72,
                background: 'rgba(255,255,255,0.95)',
                borderRadius: 6,
                padding: '0.5rem',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                gap: 4,
              }}
            >
              {logo ? (
                <img src={logo} alt="" style={{ maxWidth: 40, maxHeight: 14, objectFit: 'contain' }} />
              ) : (
                <div style={{ fontSize: '0.5rem', fontWeight: 700, color: 'var(--color-primary)', letterSpacing: 1 }}>INSIGHT</div>
              )}
              <div style={{ width: '100%', height: 8, background: '#e5e7eb', borderRadius: 2 }} />
              <div style={{ width: '100%', height: 8, background: '#e5e7eb', borderRadius: 2 }} />
              <div style={{ width: '100%', height: 10, background: 'var(--color-primary)', borderRadius: 2, opacity: 0.8 }} />
            </div>
          </div>
        </div>
      </div>

      {/* Speichern */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: '0.75rem',
          justifyContent: 'flex-end',
        }}
      >
        {saveSuccess && (
          <span
            style={{
              fontSize: '0.8125rem',
              color: 'var(--color-success)',
              fontWeight: 500,
            }}
          >
            Gespeichert!
          </span>
        )}
        {saveMutation.isError && (
          <span
            style={{
              fontSize: '0.8125rem',
              color: 'var(--color-error)',
            }}
          >
            Fehler beim Speichern
          </span>
        )}
        <button
          onClick={handleSave}
          disabled={!hasChanges || saveMutation.isPending}
          style={{
            ...btnPrimary,
            opacity: hasChanges ? 1 : 0.5,
            cursor: hasChanges ? 'pointer' : 'not-allowed',
          }}
        >
          {saveMutation.isPending ? 'Speichern...' : 'Speichern'}
        </button>
      </div>
    </div>
  );
}
