"use client";

import { useState, useEffect, useMemo } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Image, X } from "lucide-react";
import { useLocalStorage } from "@/hooks/use-local-storage";
import { cn } from "@/lib/utils";

type BackgroundType =
  | "default"
  | "gradient-blue"
  | "gradient-purple"
  | "gradient-green"
  | "gradient-orange"
  | "solid-light"
  | "solid-dark"
  | "custom-image";

interface BackgroundSettings {
  type: BackgroundType;
  customImageUrl?: string;
}

const DEFAULT_BACKGROUNDS: Array<{
  value: BackgroundType;
  label: string;
  preview: string;
  description?: string;
}> = [
  {
    value: "default",
    label: "Neutre",
    preview: "linear-gradient(135deg, oklch(0.985 0 0) 0%, oklch(0.97 0.005 260) 50%, oklch(0.985 0 0) 100%)",
    description: "Fond neutre et élégant",
  },
  {
    value: "gradient-blue",
    label: "Océan",
    preview: "linear-gradient(135deg, oklch(0.95 0.03 230) 0%, oklch(0.88 0.08 225) 50%, oklch(0.78 0.12 220) 100%)",
    description: "Dégradé bleu apaisant",
  },
  {
    value: "gradient-purple",
    label: "Améthyste",
    preview: "linear-gradient(135deg, oklch(0.95 0.04 300) 0%, oklch(0.88 0.1 295) 50%, oklch(0.78 0.15 290) 100%)",
    description: "Dégradé violet sophistiqué",
  },
  {
    value: "gradient-green",
    label: "Forêt",
    preview: "linear-gradient(135deg, oklch(0.95 0.04 160) 0%, oklch(0.88 0.1 155) 50%, oklch(0.78 0.14 150) 100%)",
    description: "Dégradé vert naturel",
  },
  {
    value: "gradient-orange",
    label: "Aurore",
    preview: "linear-gradient(135deg, oklch(0.97 0.03 80) 0%, oklch(0.92 0.08 60) 50%, oklch(0.85 0.14 45) 100%)",
    description: "Dégradé orange chaleureux",
  },
  {
    value: "solid-light",
    label: "Lumineux",
    preview: "linear-gradient(135deg, oklch(1 0 0) 0%, oklch(0.98 0.005 260) 100%)",
    description: "Fond blanc épuré",
  },
  {
    value: "solid-dark",
    label: "Minuit",
    preview: "linear-gradient(135deg, oklch(0.18 0.02 260) 0%, oklch(0.08 0.015 250) 100%)",
    description: "Fond sombre immersif",
  },
];

export function BackgroundCard() {
  const [backgroundSettings, setBackgroundSettings] =
    useLocalStorage<BackgroundSettings>("background-settings", {
      type: "default",
    });

  const currentSettings = useMemo<BackgroundSettings>(
    () => backgroundSettings || { type: "default" },
    [backgroundSettings]
  );

  const [customImageUrl, setCustomImageUrl] = useState(
    currentSettings.customImageUrl || ""
  );
  const [showCustomInput, setShowCustomInput] = useState(
    currentSettings.type === "custom-image"
  );

  // Synchroniser customImageUrl avec les settings
  useEffect(() => {
    if (
      currentSettings.type === "custom-image" &&
      currentSettings.customImageUrl
    ) {
      setCustomImageUrl(currentSettings.customImageUrl);
    }
  }, [currentSettings]);

  const applyBackground = (settings: BackgroundSettings) => {
    const root = document.documentElement;
    const pageBackground = document.querySelector(
      ".page-background"
    ) as HTMLElement;

    if (!pageBackground) return;

    // Retirer toutes les classes de fond
    pageBackground.classList.remove(
      "bg-default",
      "bg-gradient-blue",
      "bg-gradient-purple",
      "bg-gradient-green",
      "bg-gradient-orange",
      "bg-solid-light",
      "bg-solid-dark",
      "bg-custom-image"
    );

    if (settings.type === "custom-image" && settings.customImageUrl) {
      pageBackground.classList.add("bg-custom-image");
      root.style.setProperty(
        "--custom-background-image",
        `url(${settings.customImageUrl})`
      );
    } else {
      pageBackground.classList.add(`bg-${settings.type || "default"}`);
      root.style.removeProperty("--custom-background-image");
    }

    // Déclencher un événement personnalisé pour notifier les autres composants
    window.dispatchEvent(
      new CustomEvent("background-changed", { detail: settings })
    );
  };

  const handleBackgroundChange = (type: BackgroundType) => {
    if (type === "custom-image") {
      setShowCustomInput(true);
      if (customImageUrl.trim()) {
        const newSettings: BackgroundSettings = {
          type,
          customImageUrl: customImageUrl.trim(),
        };
        setBackgroundSettings(newSettings);
        applyBackground(newSettings);
      } else {
        const newSettings: BackgroundSettings = { type };
        setBackgroundSettings(newSettings);
      }
    } else {
      setShowCustomInput(false);
      const newSettings: BackgroundSettings = { type };
      setBackgroundSettings(newSettings);
      applyBackground(newSettings);
    }
  };

  const handleCustomImageSubmit = () => {
    if (customImageUrl.trim()) {
      const newSettings: BackgroundSettings = {
        type: "custom-image",
        customImageUrl: customImageUrl.trim(),
      };
      setBackgroundSettings(newSettings);
      applyBackground(newSettings);
    }
  };

  const handleRemoveCustomImage = () => {
    setCustomImageUrl("");
    setShowCustomInput(false);
    const newSettings: BackgroundSettings = { type: "default" };
    setBackgroundSettings(newSettings);
    applyBackground(newSettings);
  };

  // Appliquer le fond au chargement et quand il change
  useEffect(() => {
    if (typeof window !== "undefined") {
      applyBackground(currentSettings);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentSettings.type, currentSettings.customImageUrl]);

  return (
    <Card className="card-hover">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Image className="w-5 h-5" />
          Fond du site
        </CardTitle>
        <CardDescription>
          Personnalisez l'apparence du fond de l'application
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        <RadioGroup
          value={currentSettings.type}
          onValueChange={(value) =>
            handleBackgroundChange(value as BackgroundType)
          }
        >
          <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
            {DEFAULT_BACKGROUNDS.map((bg) => (
              <label
                key={bg.value}
                htmlFor={`bg-${bg.value}`}
                className={cn(
                  "relative flex flex-col items-center justify-center p-4 rounded-lg border-2 cursor-pointer transition-all",
                  currentSettings.type === bg.value
                    ? "border-primary bg-primary/5"
                    : "border-border hover:border-primary/50"
                )}
              >
                <RadioGroupItem
                  value={bg.value}
                  id={`bg-${bg.value}`}
                  className="sr-only"
                />
                <div
                  className="w-full h-16 rounded-md mb-2 border border-border/50"
                  style={{ background: bg.preview }}
                />
                <span className="text-xs font-medium text-center">
                  {bg.label}
                </span>
              </label>
            ))}
            <label
              htmlFor="bg-custom-image"
              className={cn(
                "relative flex flex-col items-center justify-center p-4 rounded-lg border-2 cursor-pointer transition-all",
                currentSettings.type === "custom-image"
                  ? "border-primary bg-primary/5"
                  : "border-border hover:border-primary/50"
              )}
            >
              <RadioGroupItem
                value="custom-image"
                id="bg-custom-image"
                className="sr-only"
              />
              <div className="w-full h-16 rounded-md mb-2 border border-border/50 bg-muted flex items-center justify-center">
                <Image className="w-6 h-6 text-muted-foreground" />
              </div>
              <span className="text-xs font-medium text-center">
                Image personnalisée
              </span>
            </label>
          </div>
        </RadioGroup>

        {showCustomInput && (
          <div className="space-y-3 p-4 rounded-lg bg-muted/30 border border-border">
            <div className="space-y-2">
              <Label htmlFor="custom-image-url">URL de l'image</Label>
              <div className="flex gap-2">
                <Input
                  id="custom-image-url"
                  type="url"
                  placeholder="https://example.com/image.jpg"
                  value={customImageUrl}
                  onChange={(e) => setCustomImageUrl(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      handleCustomImageSubmit();
                    }
                  }}
                />
                {customImageUrl && (
                  <Button
                    variant="outline"
                    size="icon"
                    onClick={handleRemoveCustomImage}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                )}
              </div>
            </div>
            <Button
              onClick={handleCustomImageSubmit}
              disabled={!customImageUrl.trim()}
            >
              Appliquer l'image
            </Button>
            {currentSettings.type === "custom-image" &&
              currentSettings.customImageUrl && (
                <div className="mt-3">
                  <div className="text-xs text-muted-foreground mb-2">
                    Aperçu :
                  </div>
                  <div
                    className="w-full h-32 rounded-md border border-border bg-cover bg-center bg-no-repeat"
                    style={{
                      backgroundImage: `url(${currentSettings.customImageUrl})`,
                    }}
                  />
                </div>
              )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
