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;
}

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 [logo, setLogo] = useState<string | null>(null);
  const [sidebarColor, setSidebarColor] = useState<string>('#1e293b');
  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');
      setHasChanges(false);
    }
  }, [data]);

  const saveMutation = useMutation({
    mutationFn: async (branding: {
      logo: string | null;
      sidebarColor: string;
    }) => {
      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 });
  };

  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>

        <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,
            }}
          >
            {logo ? (
              <img
                src={logo}
                alt="Logo"
                style={{
                  maxWidth: '100%',
                  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>
      </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>

      {/* 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>
  );
}
