'use client';

import { useState, useEffect, useTransition } from 'react';
import { Tag } from '@/lib/types';
import { TagsClient } from '@/clients/tags-client';
import { TAG_COLORS } from '@/lib/tag-colors';
import { Modal } from '@/components/ui/Modal';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { createTag, updateTag } from '@/actions/tags';

interface TagFormProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => Promise<void>; // Callback après succès pour refresh
  tag?: Tag | null; // Si fourni, mode édition
}

const PRESET_COLORS = TAG_COLORS;

export function TagForm({ isOpen, onClose, onSuccess, tag }: TagFormProps) {
  const [isPending, startTransition] = useTransition();
  const [formData, setFormData] = useState({
    name: '',
    color: '#3B82F6',
    isPinned: false,
  });
  const [errors, setErrors] = useState<string[]>([]);

  // Pré-remplir le formulaire en mode édition
  useEffect(() => {
    if (tag) {
      setFormData({
        name: tag.name,
        color: tag.color,
        isPinned: tag.isPinned || false,
      });
    } else {
      setFormData({
        name: '',
        color: TagsClient.generateRandomColor(),
        isPinned: false,
      });
    }
    setErrors([]);
  }, [tag, isOpen]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validation
    const validationErrors = TagsClient.validateTagData(formData);
    if (validationErrors.length > 0) {
      setErrors(validationErrors);
      return;
    }

    startTransition(async () => {
      try {
        let result;

        if (tag) {
          // Mode édition
          result = await updateTag(tag.id, {
            name: formData.name,
            color: formData.color,
            isPinned: formData.isPinned,
          });
        } else {
          // Mode création
          result = await createTag(formData.name, formData.color);
        }

        if (result.success) {
          onClose();
          // Reset form
          setFormData({
            name: '',
            color: TagsClient.generateRandomColor(),
            isPinned: false,
          });
          setErrors([]);
          // Refresh la liste des tags
          if (onSuccess) {
            await onSuccess();
          }
        } else {
          setErrors([result.error || 'Erreur inconnue']);
        }
      } catch (error) {
        setErrors([error instanceof Error ? error.message : 'Erreur inconnue']);
      }
    });
  };

  const handleColorSelect = (color: string) => {
    setFormData((prev) => ({ ...prev, color }));
    setErrors([]);
  };

  const handleCustomColorChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData((prev) => ({ ...prev, color: e.target.value }));
    setErrors([]);
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={tag ? 'Éditer le tag' : 'Nouveau tag'}
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Nom du tag */}
        <div>
          <label
            htmlFor="tag-name"
            className="block text-sm font-medium text-slate-200 mb-2"
          >
            Nom du tag
          </label>
          <Input
            id="tag-name"
            type="text"
            value={formData.name}
            onChange={(e) => {
              setFormData((prev) => ({ ...prev, name: e.target.value }));
              setErrors([]);
            }}
            placeholder="Nom du tag..."
            maxLength={50}
            disabled={isPending}
            className="w-full"
          />
        </div>

        {/* Sélecteur de couleur */}
        <div>
          <label className="block text-sm font-medium text-slate-200 mb-3">
            Couleur du tag
          </label>

          {/* Aperçu de la couleur sélectionnée */}
          <div className="flex items-center gap-3 mb-4 p-3 bg-slate-800 rounded-lg border border-slate-600">
            <div
              className="w-6 h-6 rounded-full border-2 border-slate-500"
              style={{ backgroundColor: formData.color }}
            />
            <span className="text-slate-200 font-medium">
              {formData.name || 'Aperçu du tag'}
            </span>
          </div>

          {/* Couleurs prédéfinies */}
          <div className="grid grid-cols-6 gap-2 mb-4">
            {PRESET_COLORS.map((color) => (
              <button
                key={color}
                type="button"
                onClick={() => handleColorSelect(color)}
                className={`w-10 h-10 rounded-lg border-2 transition-all hover:scale-110 ${
                  formData.color === color
                    ? 'border-white shadow-lg'
                    : 'border-slate-600 hover:border-slate-400'
                }`}
                style={{ backgroundColor: color }}
                title={color}
              />
            ))}
          </div>

          {/* Couleur personnalisée */}
          <div className="flex items-center gap-3">
            <label htmlFor="custom-color" className="text-sm text-slate-400">
              Couleur personnalisée :
            </label>
            <input
              id="custom-color"
              type="color"
              value={formData.color}
              onChange={handleCustomColorChange}
              disabled={isPending}
              className="w-12 h-8 rounded border border-slate-600 bg-slate-800 cursor-pointer disabled:cursor-not-allowed"
            />
            <Input
              type="text"
              value={formData.color}
              onChange={(e) => {
                if (TagsClient.isValidColor(e.target.value)) {
                  handleCustomColorChange(
                    e as React.ChangeEvent<HTMLInputElement>
                  );
                }
              }}
              placeholder="#RRGGBB"
              maxLength={7}
              disabled={isPending}
              className="w-24 text-xs font-mono"
            />
          </div>
        </div>

        {/* Objectif principal */}
        <div className="space-y-2">
          <label className="block text-sm font-mono font-medium text-slate-300 uppercase tracking-wider">
            Type de tag
          </label>
          <div className="flex items-center gap-3">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={formData.isPinned}
                onChange={(e) =>
                  setFormData((prev) => ({
                    ...prev,
                    isPinned: e.target.checked,
                  }))
                }
                disabled={isPending}
                className="w-4 h-4 rounded border border-slate-600 bg-slate-800 text-purple-600 focus:ring-purple-500 focus:ring-2 disabled:cursor-not-allowed"
              />
              <span className="text-sm text-slate-300">
                🎯 Objectif principal
              </span>
            </label>
          </div>
          <p className="text-xs text-slate-400">
            Les tâches avec ce tag apparaîtront dans la section &quot;Objectifs
            Principaux&quot; au-dessus du Kanban
          </p>
        </div>

        {/* Erreurs */}
        {errors.length > 0 && (
          <div className="bg-red-900/20 border border-red-500/30 rounded-lg p-3">
            <div className="text-red-400 text-sm space-y-1">
              {errors.map((error, index) => (
                <div key={index}>• {error}</div>
              ))}
            </div>
          </div>
        )}

        {/* Actions */}
        <div className="flex justify-end gap-3 pt-4 border-t border-slate-700">
          <Button
            type="button"
            variant="secondary"
            onClick={onClose}
            disabled={isPending}
          >
            Annuler
          </Button>
          <Button
            type="submit"
            variant="primary"
            disabled={isPending || !formData.name.trim()}
          >
            {isPending ? 'Enregistrement...' : tag ? 'Mettre à jour' : 'Créer'}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
