'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/Button';
import { Card, CardContent } from '@/components/ui/Card';
import { useUserPreferences } from '@/contexts/UserPreferencesContext';
import { PRESET_BACKGROUNDS } from '@/lib/ui-config';

export function BackgroundImageSelector() {
  const { preferences, updateViewPreferences } = useUserPreferences();
  const [customUrl, setCustomUrl] = useState('');
  const [showCustomInput, setShowCustomInput] = useState(false);
  const [showAdvancedOptions, setShowAdvancedOptions] = useState(false);

  const currentBackground = preferences?.viewPreferences?.backgroundImage;
  const backgroundBlur = preferences?.viewPreferences?.backgroundBlur || 0;
  const backgroundOpacity =
    preferences?.viewPreferences?.backgroundOpacity || 100;
  const customImages = preferences?.viewPreferences?.customImages || [];

  const handlePresetSelect = (presetId: string) => {
    const backgroundImage = presetId === 'none' ? undefined : presetId;
    updateViewPreferences({ backgroundImage });
  };

  const handleCustomUrlSubmit = () => {
    if (!customUrl.trim()) return;

    const url = customUrl.trim();

    // Ajouter l'image aux images personnalisées si elle n'existe pas déjà
    if (!customImages.includes(url)) {
      const newCustomImages = [...customImages, url];
      updateViewPreferences({
        backgroundImage: url,
        customImages: newCustomImages,
      });
    } else {
      // Si elle existe déjà, juste la sélectionner
      updateViewPreferences({ backgroundImage: url });
    }

    setCustomUrl('');
    setShowCustomInput(false);
  };

  const handleRemoveCustomImage = (urlToRemove: string) => {
    const newCustomImages = customImages.filter((url) => url !== urlToRemove);
    updateViewPreferences({
      customImages: newCustomImages,
      backgroundImage:
        currentBackground === urlToRemove ? undefined : currentBackground,
    });
  };

  const handleSelectCustomImage = (url: string) => {
    updateViewPreferences({ backgroundImage: url });
  };

  const handleBlurChange = (blur: number) => {
    updateViewPreferences({ backgroundBlur: blur });
  };

  const handleOpacityChange = (opacity: number) => {
    updateViewPreferences({ backgroundOpacity: opacity });
  };

  // Réinitialiser les options avancées quand l'image change
  useEffect(() => {
    setShowAdvancedOptions(false);
  }, [currentBackground]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-mono font-semibold text-[var(--foreground)]">
            Image de fond
          </h3>
          <p className="text-sm text-[var(--muted-foreground)] mt-1">
            Personnalisez l&apos;arrière-plan de toutes les pages
          </p>
        </div>
        <div className="text-sm text-[var(--muted-foreground)]">
          {currentBackground ? (
            <span className="font-medium text-[var(--primary)]">
              {PRESET_BACKGROUNDS.find((p) => p.id === currentBackground)
                ?.name || 'Personnalisé'}
            </span>
          ) : (
            <span className="font-medium text-[var(--muted-foreground)]">
              Aucune
            </span>
          )}
        </div>
      </div>

      {/* Aperçu actuel */}
      <Card>
        <CardContent className="p-4">
          <div className="text-sm text-[var(--muted-foreground)] mb-3">
            Aperçu actuel :
          </div>
          <div
            className="w-full h-24 rounded-lg border border-[var(--border)]/30 overflow-hidden"
            style={{
              backgroundImage:
                currentBackground &&
                !PRESET_BACKGROUNDS.find((p) => p.id === currentBackground)
                  ? `url("${currentBackground}")`
                  : PRESET_BACKGROUNDS.find((p) => p.id === currentBackground)
                      ?.preview || 'var(--background)',
              backgroundSize: 'cover',
              backgroundPosition: 'center',
              backgroundRepeat: 'no-repeat',
            }}
          />
        </CardContent>
      </Card>

      {/* Images prédéfinies */}
      <Card variant="glass">
        <CardContent className="p-4">
          <div className="text-sm text-[var(--muted-foreground)] mb-4">
            Images prédéfinies :
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            {PRESET_BACKGROUNDS.map((preset) => (
              <Button
                key={preset.id}
                onClick={() => handlePresetSelect(preset.id)}
                variant={
                  currentBackground === preset.id ? 'selected' : 'secondary'
                }
                className="p-3 h-auto text-left justify-start"
              >
                <div className="flex items-start gap-3">
                  {/* Aperçu */}
                  <div
                    className="w-12 h-8 rounded border border-[var(--border)]/30 flex-shrink-0"
                    style={{ background: preset.preview }}
                  />

                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-[var(--foreground)] mb-1">
                      {preset.name}
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)] leading-relaxed">
                      {preset.description}
                    </div>
                    {currentBackground === preset.id && (
                      <div className="mt-1 text-xs text-[var(--primary)] font-medium">
                        ✓ Sélectionné
                      </div>
                    )}
                  </div>
                </div>
              </Button>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Images personnalisées */}
      {customImages.length > 0 && (
        <Card variant="glass">
          <CardContent className="p-4">
            <div className="text-sm text-[var(--muted-foreground)] mb-4">
              Images personnalisées :
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {customImages.map((url, index) => (
                <div key={url} className="relative">
                  <Button
                    onClick={() => handleSelectCustomImage(url)}
                    variant={
                      currentBackground === url ? 'selected' : 'secondary'
                    }
                    className="p-3 h-auto text-left justify-start w-full"
                  >
                    <div className="flex items-start gap-3 w-full">
                      {/* Aperçu */}
                      <div
                        className="w-12 h-8 rounded border border-[var(--border)]/30 flex-shrink-0 bg-cover bg-center"
                        style={{ backgroundImage: `url("${url}")` }}
                      />

                      <div className="flex-1 min-w-0 pr-8">
                        <div className="font-medium text-[var(--foreground)] mb-1">
                          Image {index + 1}
                        </div>
                        <div className="text-xs text-[var(--muted-foreground)] leading-relaxed truncate">
                          {url.length > 25 ? `${url.substring(0, 25)}...` : url}
                        </div>
                        {currentBackground === url && (
                          <div className="mt-1 text-xs text-[var(--primary)] font-medium">
                            ✓ Sélectionné
                          </div>
                        )}
                      </div>
                    </div>
                  </Button>

                  {/* Bouton supprimer - positionné absolument */}
                  <Button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleRemoveCustomImage(url);
                    }}
                    variant="destructive"
                    size="sm"
                    className="absolute top-2 right-2 px-2 py-1 text-xs h-6 w-6 min-w-0"
                  >
                    ×
                  </Button>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* URL personnalisée */}
      <Card>
        <CardContent className="p-4">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <h4 className="text-sm font-medium text-[var(--foreground)]">
                  URL personnalisée
                </h4>
                <p className="text-xs text-[var(--muted-foreground)] mt-1">
                  Ajoutez votre propre image de fond
                </p>
              </div>
              <Button
                onClick={() => setShowCustomInput(!showCustomInput)}
                variant="secondary"
                size="sm"
              >
                {showCustomInput ? 'Masquer' : 'Ajouter'}
              </Button>
            </div>

            {showCustomInput && (
              <div className="space-y-3">
                <div className="flex gap-2">
                  <input
                    type="url"
                    placeholder="https://example.com/image.jpg"
                    value={customUrl}
                    onChange={(e) => setCustomUrl(e.target.value)}
                    className="flex-1 h-10 px-3 py-2 text-sm border border-[var(--border)]/50 bg-[var(--input)] text-[var(--foreground)] placeholder:text-[var(--muted-foreground)] focus:border-[var(--primary)]/70 focus:ring-1 focus:ring-[var(--primary)]/20 rounded-md focus-visible:outline-none transition-colors"
                    autoComplete="off"
                    spellCheck="false"
                  />
                  <Button
                    onClick={handleCustomUrlSubmit}
                    disabled={!customUrl.trim()}
                    className="px-4"
                  >
                    Appliquer
                  </Button>
                </div>
                <div className="p-3 bg-[var(--card)] border border-[var(--border)] rounded-lg">
                  <div className="flex items-start gap-2">
                    <div className="text-[var(--accent)] text-sm mt-0.5">
                      💡
                    </div>
                    <div className="text-xs text-[var(--muted-foreground)]">
                      <strong className="text-[var(--foreground)]">
                        Conseil performance :
                      </strong>{' '}
                      Utilisez des images optimisées (&lt; 500KB) et hébergées
                      sur un CDN pour de meilleures performances. Les formats
                      WebP et AVIF sont recommandés.
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Options avancées - seulement pour les URLs personnalisées */}
      {currentBackground &&
        !PRESET_BACKGROUNDS.find((p) => p.id === currentBackground) && (
          <Card>
            <CardContent className="p-4">
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="text-sm font-medium text-[var(--foreground)]">
                      Options avancées
                    </h4>
                    <p className="text-xs text-[var(--muted-foreground)] mt-1">
                      Ajustez l&apos;effet de votre image personnalisée
                    </p>
                  </div>
                  <Button
                    onClick={() => setShowAdvancedOptions(!showAdvancedOptions)}
                    variant="secondary"
                    size="sm"
                  >
                    {showAdvancedOptions ? 'Masquer' : 'Afficher'}
                  </Button>
                </div>

                {showAdvancedOptions && (
                  <div className="space-y-4">
                    {/* Contrôle du blur */}
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <label className="text-sm text-[var(--foreground)]">
                          Flou d&apos;arrière-plan
                        </label>
                        <span className="text-xs text-[var(--muted-foreground)]">
                          {backgroundBlur}px
                        </span>
                      </div>
                      <input
                        type="range"
                        min="0"
                        max="20"
                        step="1"
                        value={backgroundBlur}
                        onChange={(e) =>
                          handleBlurChange(Number(e.target.value))
                        }
                        className="w-full h-2 bg-[var(--border)] rounded-lg appearance-none cursor-pointer slider"
                      />
                      <div className="flex justify-between text-xs text-[var(--muted-foreground)]">
                        <span>Aucun</span>
                        <span>Très flou</span>
                      </div>
                    </div>

                    {/* Contrôle de l'opacité */}
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <label className="text-sm text-[var(--foreground)]">
                          Opacité de l&apos;image
                        </label>
                        <span className="text-xs text-[var(--muted-foreground)]">
                          {backgroundOpacity}%
                        </span>
                      </div>
                      <input
                        type="range"
                        min="10"
                        max="100"
                        step="5"
                        value={backgroundOpacity}
                        onChange={(e) =>
                          handleOpacityChange(Number(e.target.value))
                        }
                        className="w-full h-2 bg-[var(--border)] rounded-lg appearance-none cursor-pointer slider"
                      />
                      <div className="flex justify-between text-xs text-[var(--muted-foreground)]">
                        <span>Très transparent</span>
                        <span>Opaque</span>
                      </div>
                    </div>

                    {/* Aperçu en temps réel */}
                    <div className="space-y-2">
                      <label className="text-sm text-[var(--foreground)]">
                        Aperçu avec les effets appliqués :
                      </label>
                      <div
                        className="w-full h-16 rounded-lg border border-[var(--border)]/30 overflow-hidden"
                        style={{
                          backgroundImage:
                            currentBackground &&
                            !PRESET_BACKGROUNDS.find(
                              (p) => p.id === currentBackground
                            )
                              ? `url(${currentBackground})`
                              : PRESET_BACKGROUNDS.find(
                                  (p) => p.id === currentBackground
                                )?.preview || 'var(--background)',
                          backgroundSize: 'cover',
                          backgroundPosition: 'center',
                          backgroundRepeat: 'no-repeat',
                          filter: `blur(${backgroundBlur}px)`,
                          opacity: backgroundOpacity / 100,
                        }}
                      />
                    </div>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        )}
    </div>
  );
}
