'use client';

import { useState, useEffect, useCallback, useTransition } from 'react';
import { DailyCheckbox } from '@/lib/types';
import { tasksClient } from '@/clients/tasks-client';
import { Button } from '@/components/ui/Button';
import { formatDateSmart, parseDate } from '@/lib/date-utils';
import { Input } from '@/components/ui/Input';
import { addTodoToTask, toggleCheckbox } from '@/actions/daily';

interface RelatedTodosProps {
  taskId: string;
}

export function RelatedTodos({ taskId }: RelatedTodosProps) {
  const [checkboxes, setCheckboxes] = useState<DailyCheckbox[]>([]);
  const [loading, setLoading] = useState(true);
  const [newTodoText, setNewTodoText] = useState('');
  const [newTodoDate, setNewTodoDate] = useState('');
  const [showAddForm, setShowAddForm] = useState(false);
  const [isPending, startTransition] = useTransition();

  const loadCheckboxes = useCallback(async () => {
    try {
      setLoading(true);
      const data = await tasksClient.getTaskCheckboxes(taskId);
      setCheckboxes(data);
    } catch (error) {
      console.error('Erreur lors du chargement des todos:', error);
    } finally {
      setLoading(false);
    }
  }, [taskId]);

  useEffect(() => {
    loadCheckboxes();
  }, [loadCheckboxes]);

  const handleAddTodo = () => {
    if (!newTodoText.trim()) return;

    startTransition(async () => {
      try {
        // Si une date est spécifiée, l'utiliser, sinon undefined (aujourd'hui par défaut)
        const targetDate = newTodoDate ? parseDate(newTodoDate) : undefined;

        const result = await addTodoToTask(taskId, newTodoText, targetDate);

        if (result.success) {
          // Recharger les checkboxes
          await loadCheckboxes();
          setNewTodoText('');
          setNewTodoDate('');
          setShowAddForm(false);
        } else {
          console.error("Erreur lors de l'ajout du todo:", result.error);
        }
      } catch (error) {
        console.error("Erreur lors de l'ajout du todo:", error);
      }
    });
  };

  const handleToggleCheckbox = (checkboxId: string) => {
    startTransition(async () => {
      try {
        const result = await toggleCheckbox(checkboxId);
        if (result.success) {
          // Recharger les checkboxes
          await loadCheckboxes();
        } else {
          console.error('Erreur lors du toggle:', result.error);
        }
      } catch (error) {
        console.error('Erreur lors du toggle:', error);
      }
    });
  };

  const formatDate = (date: Date | string) => {
    try {
      const dateObj = typeof date === 'string' ? parseDate(date) : date;
      if (isNaN(dateObj.getTime())) {
        return 'Date invalide';
      }
      return formatDateSmart(dateObj);
    } catch (error) {
      console.error('Erreur formatage date:', error, date);
      return 'Date invalide';
    }
  };

  if (loading) {
    return (
      <div className="space-y-3">
        <label className="block text-sm font-mono font-medium text-[var(--muted-foreground)] uppercase tracking-wider">
          Todos reliés
        </label>
        <div className="text-sm text-[var(--muted-foreground)] font-mono">
          Chargement...
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <label className="block text-sm font-mono font-medium text-[var(--muted-foreground)] uppercase tracking-wider">
          Todos reliés ({checkboxes.length})
        </label>
      </div>

      {/* Liste des todos existants */}
      {checkboxes.length > 0 ? (
        <div className="space-y-2 max-h-32 overflow-y-auto pr-2">
          {checkboxes.map((checkbox) => (
            <div
              key={checkbox.id}
              className={`flex items-start gap-3 p-3 bg-[var(--card)] rounded-lg border border-[var(--border)] transition-all hover:bg-[var(--muted)]/20 ${isPending ? 'opacity-60' : ''}`}
            >
              <input
                type="checkbox"
                checked={checkbox.isChecked}
                onChange={() => handleToggleCheckbox(checkbox.id)}
                disabled={isPending}
                className="w-4 h-4 mt-0.5 rounded border-[var(--border)] bg-[var(--input)] text-[var(--primary)] cursor-pointer disabled:cursor-not-allowed disabled:opacity-50"
              />
              <div className="flex-1 min-w-0">
                <div
                  className={`text-sm font-mono ${checkbox.isChecked ? 'line-through text-[var(--muted-foreground)]' : 'text-[var(--foreground)]'}`}
                >
                  {checkbox.text}
                </div>
                <div className="text-xs text-[var(--muted-foreground)] font-mono mt-1 flex items-center gap-1">
                  <span>📅</span>
                  {formatDate(checkbox.date)}
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-sm text-[var(--muted-foreground)] font-mono italic p-3 bg-[var(--muted)]/20 rounded-lg border border-dashed border-[var(--border)]">
          Aucun todo relié à cette tâche
        </div>
      )}

      {/* Section d'ajout */}
      <div className="pt-2 border-t border-[var(--border)]/50">
        {!showAddForm ? (
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => setShowAddForm(true)}
            className="w-full justify-center text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
          >
            <span className="mr-2">+</span>
            Ajouter un todo
          </Button>
        ) : (
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <div className="text-sm font-mono font-medium text-[var(--muted-foreground)]">
                Nouveau todo
              </div>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => {
                  setShowAddForm(false);
                  setNewTodoText('');
                  setNewTodoDate('');
                }}
                className="text-[var(--muted-foreground)] hover:text-[var(--foreground)] px-2"
              >
                ✕
              </Button>
            </div>

            <Input
              placeholder="Texte du todo..."
              value={newTodoText}
              onChange={(e) => setNewTodoText(e.target.value)}
              disabled={isPending}
              autoFocus
            />

            <div className="flex gap-2">
              <Input
                type="date"
                value={newTodoDate}
                onChange={(e) => setNewTodoDate(e.target.value)}
                disabled={isPending}
                placeholder="Date (optionnel)"
                className="flex-1"
              />
              <Button
                type="button"
                variant="primary"
                size="sm"
                onClick={handleAddTodo}
                disabled={!newTodoText.trim() || isPending}
              >
                {isPending ? 'Ajout...' : 'Ajouter'}
              </Button>
            </div>

            {!newTodoDate && (
              <div className="text-xs text-[var(--muted-foreground)] font-mono">
                💡 Sans date, le todo sera ajouté à aujourd&apos;hui
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
