'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { DailyCheckbox, DailyCheckboxType } from '@/lib/types';
import { Input } from '@/components/ui/Input';
import { EditCheckboxModal } from './EditCheckboxModal';
import { getTaskEmoji } from '@/lib/task-emoji';
import { Emoji } from '@/components/ui/Emoji';

interface DailyCheckboxItemProps {
  checkbox: DailyCheckbox;
  onToggle: (checkboxId: string) => Promise<void>;
  onUpdate: (
    checkboxId: string,
    text: string,
    type: DailyCheckboxType,
    taskId?: string,
    date?: Date
  ) => Promise<void>;
  onDelete: (checkboxId: string) => Promise<void>;
  saving?: boolean;
}

export function DailyCheckboxItem({
  checkbox,
  onToggle,
  onUpdate,
  onDelete,
  saving = false,
}: DailyCheckboxItemProps) {
  const [inlineEditingId, setInlineEditingId] = useState<string | null>(null);
  const [inlineEditingText, setInlineEditingText] = useState('');
  const [editingCheckbox, setEditingCheckbox] = useState<DailyCheckbox | null>(
    null
  );
  const [optimisticChecked, setOptimisticChecked] = useState<boolean | null>(
    null
  );

  // État optimiste local pour une réponse immédiate
  const isChecked =
    optimisticChecked !== null ? optimisticChecked : checkbox.isChecked;

  // Synchroniser l'état optimiste avec les changements externes
  useEffect(() => {
    if (
      optimisticChecked !== null &&
      optimisticChecked === checkbox.isChecked
    ) {
      // L'état serveur a été mis à jour, on peut reset l'optimiste
      setOptimisticChecked(null);
    }
  }, [checkbox.isChecked, optimisticChecked]);

  // Handler optimiste pour le toggle
  const handleOptimisticToggle = async () => {
    const newCheckedState = !isChecked;

    // Mise à jour optimiste immédiate
    setOptimisticChecked(newCheckedState);

    try {
      await onToggle(checkbox.id);
      // Reset l'état optimiste après succès
      setOptimisticChecked(null);
    } catch (error) {
      // Rollback en cas d'erreur
      setOptimisticChecked(null);
      console.error('Erreur lors du toggle:', error);
    }
  };

  // Édition inline simple
  const handleStartInlineEdit = () => {
    setInlineEditingId(checkbox.id);
    setInlineEditingText(checkbox.text);
  };

  const handleSaveInlineEdit = async () => {
    if (!inlineEditingText.trim()) return;

    try {
      await onUpdate(
        checkbox.id,
        inlineEditingText.trim(),
        checkbox.type,
        checkbox.taskId
      );
      setInlineEditingId(null);
      setInlineEditingText('');
    } catch (error) {
      console.error('Erreur lors de la modification:', error);
    }
  };

  const handleCancelInlineEdit = () => {
    setInlineEditingId(null);
    setInlineEditingText('');
  };

  const handleInlineEditKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSaveInlineEdit();
    } else if (e.key === 'Escape') {
      e.preventDefault();
      handleCancelInlineEdit();
    }
  };

  // Modal d'édition avancée
  const handleStartAdvancedEdit = () => {
    setEditingCheckbox(checkbox);
  };

  const handleSaveAdvancedEdit = async (
    text: string,
    type: DailyCheckboxType,
    taskId?: string,
    date?: Date
  ) => {
    await onUpdate(checkbox.id, text, type, taskId, date);
    setEditingCheckbox(null);
  };

  const handleCloseAdvancedEdit = () => {
    setEditingCheckbox(null);
  };

  // Vérifier si la tâche est archivée
  const isArchived = checkbox.isArchived;

  // Obtenir l'emoji de la tâche associée si elle existe
  const taskEmoji = checkbox.task
    ? getTaskEmoji(checkbox.task, undefined)
    : null;

  return (
    <>
      <div
        className={`flex items-center gap-3 px-3 py-2 sm:py-1.5 sm:gap-2 rounded border transition-colors group ${
          checkbox.type === 'meeting'
            ? 'border-l-4 border-l-blue-500 border-t-[var(--border)]/30 border-r-[var(--border)]/30 border-b-[var(--border)]/30 hover:border-t-[var(--border)] hover:border-r-[var(--border)] hover:border-b-[var(--border)]'
            : 'border-l-4 border-l-green-500 border-t-[var(--border)]/30 border-r-[var(--border)]/30 border-b-[var(--border)]/30 hover:border-t-[var(--border)] hover:border-r-[var(--border)] hover:border-b-[var(--border)]'
        } ${isArchived ? 'opacity-60 bg-[var(--muted)]/20' : ''}`}
      >
        {/* Checkbox */}
        <input
          type="checkbox"
          checked={isArchived ? false : isChecked}
          onChange={handleOptimisticToggle}
          disabled={saving || isArchived}
          className={`w-4 h-4 md:w-3.5 md:h-3.5 rounded border text-[var(--primary)] focus:ring-[var(--primary)]/20 focus:ring-1 ${
            isArchived
              ? 'border-[var(--muted)] cursor-not-allowed opacity-50'
              : 'border-[var(--border)]'
          }`}
        />

        {/* Contenu principal */}
        {inlineEditingId === checkbox.id ? (
          <Input
            value={inlineEditingText}
            onChange={(e) => setInlineEditingText(e.target.value)}
            onKeyDown={handleInlineEditKeyPress}
            onBlur={handleSaveInlineEdit}
            autoFocus
            className="flex-1 h-7 text-sm"
          />
        ) : (
          <div className="flex-1 flex items-center gap-0.5">
            {/* Emoji de la tâche associée */}
            {taskEmoji && (
              <span className="text-sm sm:text-xs flex-shrink-0 flex items-center leading-none">
                <Emoji emoji={taskEmoji} />
              </span>
            )}

            {/* Texte cliquable pour édition inline */}
            <span
              className={`flex-1 text-sm sm:text-xs font-mono transition-all cursor-pointer hover:bg-[var(--muted)]/50 py-0.5 px-1 rounded ${
                isArchived || checkbox.isChecked
                  ? 'line-through text-[var(--muted-foreground)]'
                  : 'text-[var(--foreground)]'
              }`}
              onClick={handleStartInlineEdit}
              title="Cliquer pour éditer le texte"
            >
              {checkbox.text}
            </span>

            {/* Icône d'édition avancée */}
            <button
              onClick={handleStartAdvancedEdit}
              disabled={saving}
              className="opacity-0 group-hover:opacity-100 w-5 h-5 rounded-full bg-[var(--muted)]/50 hover:bg-[var(--muted)] border border-[var(--border)]/30 hover:border-[var(--border)] flex items-center justify-center transition-all duration-200 text-[var(--foreground)] text-xs"
              title="Éditer les options (type, liaison tâche)"
            >
              ✏️
            </button>
          </div>
        )}

        {/* Lien vers la tâche si liée */}
        {checkbox.task && (
          <Link
            href={`/kanban?taskId=${checkbox.task.id}`}
            className="text-xs text-[var(--primary)] hover:text-[var(--primary)]/80 font-mono truncate max-w-[100px]"
            title={`Tâche: ${checkbox.task.title}`}
          >
            {checkbox.task.title}
          </Link>
        )}

        {/* Bouton de suppression */}
        <button
          onClick={() => onDelete(checkbox.id)}
          disabled={saving}
          className="opacity-0 group-hover:opacity-100 w-5 h-5 rounded-full bg-[var(--destructive)]/20 hover:bg-[var(--destructive)]/30 border border-[var(--destructive)]/30 hover:border-[var(--destructive)]/50 flex items-center justify-center transition-all duration-200 text-[var(--destructive)] text-xs"
          title="Supprimer"
        >
          ×
        </button>
      </div>

      {/* Modal d'édition avancée */}
      {editingCheckbox && (
        <EditCheckboxModal
          checkbox={editingCheckbox}
          isOpen={true}
          onClose={handleCloseAdvancedEdit}
          onSave={handleSaveAdvancedEdit}
          saving={saving}
        />
      )}
    </>
  );
}
