import { TabloUpdate, UserTablo } from "@xtablo/shared/types/tablos.types";
import { Button } from "@xtablo/ui/components/button";
import { Input } from "@xtablo/ui/components/input";
import { useEffect, useRef, useState } from "react";
import { ClickOutside } from "./ClickOutside";
import { ImageColorPicker } from "./ImageColorPicker";

interface TabloSettingsSectionProps {
  tablo: UserTablo;
  isAdmin: boolean;
  onEdit: (updatedTablo: TabloUpdate & { id: string }) => void;
}

export const TabloSettingsSection = ({ tablo, isAdmin, onEdit }: TabloSettingsSectionProps) => {
  const [editData, setEditData] = useState<UserTablo | null>(tablo);
  const [isEditingName, setIsEditingName] = useState(false);
  const [creationMode, setCreationMode] = useState<"image" | "color">("color");
  const [selectedColor, setSelectedColor] = useState(tablo.color || "bg-blue-500");

  const nameInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setEditData(tablo);
    setSelectedColor(tablo.color || "bg-blue-500");
  }, [tablo]);

  // Auto-focus name input when editing
  useEffect(() => {
    if (isEditingName && nameInputRef.current) {
      nameInputRef.current.focus();
      nameInputRef.current.select();
    }
  }, [isEditingName]);

  const handleSaveEdit = () => {
    if (editData && onEdit) {
      const updatedTablo: TabloUpdate & { id: string } = {
        id: editData.id,
        name: editData.name,
        color: creationMode === "color" ? selectedColor : null,
        // Note: status is now computed from etapes and cannot be changed directly
      };
      onEdit(updatedTablo);
    }
  };

  const currentData = editData || tablo;

  return (
    <div className="space-y-6">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Paramètres</h1>
          <p className="text-muted-foreground mt-1">Configurez votre tablo et gérez les accès</p>
        </div>
        {isAdmin && (
          <Button onClick={handleSaveEdit} className="px-6">
            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M5 13l4 4L19 7"
              />
            </svg>
            Sauvegarder les modifications
          </Button>
        )}
      </div>

      {!isAdmin ? (
        /* Read-only view for non-admins */
        <div className="space-y-6">
          {/* Tablo Preview */}
          <div className="bg-card rounded-lg border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Aperçu</h3>
            <div className="relative h-32 rounded-lg overflow-hidden">
              {tablo.image ? (
                <img src={tablo.image} alt={tablo.name} className="w-full h-full object-cover" />
              ) : (
                <div
                  className={`w-full h-full ${
                    tablo.color || "bg-gray-400"
                  } flex items-center justify-center`}
                >
                  <h3 className="text-white font-bold text-2xl text-center px-4">{tablo.name}</h3>
                </div>
              )}
            </div>
          </div>

          {/* Status and Role */}
          <div className="bg-card rounded-lg border border-border p-6">
            <div className="flex gap-8">
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-foreground mb-4">Statut</h3>
                <div className="text-foreground">
                  {currentData.status === "todo" && "À faire"}
                  {currentData.status === "in_progress" && "En cours"}
                  {currentData.status === "done" && "Terminé"}
                </div>
              </div>
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-foreground mb-4">Votre rôle</h3>
                <div className="text-foreground">
                  {tablo.is_admin ? "Administrateur" : "Invité"}
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        /* Editable view for admins */
        <div className="space-y-6">
          {/* Name Edit */}
          <div className="bg-card rounded-lg border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Nom du tablo</h3>
            {isEditingName ? (
              <ClickOutside onClickOutside={() => setIsEditingName(false)}>
                <Input
                  ref={nameInputRef}
                  type="text"
                  value={editData?.name}
                  onChange={(e) =>
                    setEditData((prev) => (prev ? { ...prev, name: e.target.value } : null))
                  }
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      setIsEditingName(false);
                    }
                  }}
                  placeholder="Nom du tablo"
                />
              </ClickOutside>
            ) : (
              <div
                className="text-lg font-medium text-foreground cursor-text hover:text-primary hover:border-primary transition-colors border-2 border-dashed border-muted-foreground/30 rounded px-3 py-2"
                onClick={() => setIsEditingName(true)}
              >
                {editData?.name}
              </div>
            )}
          </div>

          {/* Color/Image Picker */}
          <div className="bg-card rounded-lg border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Apparence</h3>
            <ImageColorPicker
              creationMode={creationMode}
              setCreationMode={setCreationMode}
              selectedColor={selectedColor}
              setSelectedColor={setSelectedColor}
            />
          </div>

          {/* Status (Read-only - computed from etapes) */}
          <div className="bg-card rounded-lg border border-border p-6">
            <h3 className="text-lg font-semibold text-foreground mb-4">Statut</h3>
            <div className="flex items-center gap-3">
              <div className="text-foreground">
                {currentData.status === "todo" && "À faire"}
                {currentData.status === "in_progress" && "En cours"}
                {currentData.status === "done" && "Terminé"}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
