'use client';

import { useState, useEffect } from 'react';
import { CheckSquare2, Calendar } from 'lucide-react';
import {
  DailyCheckbox,
  DailyCheckboxType,
  Task,
  TaskStatus,
} from '@/lib/types';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Modal } from '@/components/ui/Modal';
import { TagDisplay } from '@/components/ui/TagDisplay';
import { Card } from '@/components/ui/Card';
import { SearchInput } from '@/components/ui/SearchInput';
import { StatusBadge } from '@/components/ui/StatusBadge';
import { ToggleButton } from '@/components/ui/ToggleButton';
import { DateTimeInput } from '@/components/ui/DateTimeInput';
import { tasksClient } from '@/clients/tasks-client';
import { getStatusConfig } from '@/lib/status-config';

interface EditCheckboxModalProps {
  checkbox: DailyCheckbox;
  isOpen: boolean;
  onClose: () => void;
  onSave: (
    text: string,
    type: DailyCheckboxType,
    taskId?: string,
    date?: Date
  ) => Promise<void>;
  saving?: boolean;
}

export function EditCheckboxModal({
  checkbox,
  isOpen,
  onClose,
  onSave,
  saving = false,
}: EditCheckboxModalProps) {
  const [text, setText] = useState(checkbox.text);
  const [type, setType] = useState<DailyCheckboxType>(checkbox.type);
  const [taskId, setTaskId] = useState<string | undefined>(checkbox.taskId);
  const [date, setDate] = useState<Date>(checkbox.date);
  const [selectedTask, setSelectedTask] = useState<Task | undefined>(undefined);
  const [allTasks, setAllTasks] = useState<Task[]>([]);
  const [tasksLoading, setTasksLoading] = useState(false);
  const [taskSearch, setTaskSearch] = useState('');

  // Charger toutes les tâches au début
  useEffect(() => {
    if (isOpen) {
      setTasksLoading(true);
      tasksClient
        .getTasks()
        .then((response) => {
          setAllTasks(response.data);
          // Trouver la tâche sélectionnée si elle existe
          if (taskId) {
            const task = response.data.find((t: Task) => t.id === taskId);
            setSelectedTask(task);
          }
        })
        .catch(console.error)
        .finally(() => setTasksLoading(false));
    }
  }, [isOpen, taskId]);

  // Mettre à jour la tâche sélectionnée quand taskId change
  useEffect(() => {
    if (taskId && allTasks.length > 0) {
      const task = allTasks.find((t: Task) => t.id === taskId);
      setSelectedTask(task);
    } else {
      setSelectedTask(undefined);
    }
  }, [taskId, allTasks]);

  // Fonction pour identifier les statuts terminés
  const isCompletedStatus = (status: string): boolean => {
    return ['done', 'cancelled', 'archived'].includes(status);
  };

  // Filtrer et trier les tâches selon la recherche et exclure les tâches avec des tags "objectif principal"
  const filteredTasks = allTasks
    .filter((task) => {
      // Exclure les tâches avec des tags marqués comme "objectif principal" (isPinned = true)
      if (task.tagDetails && task.tagDetails.some((tag) => tag.isPinned)) {
        return false;
      }

      // Filtrer selon la recherche
      const searchLower = taskSearch.toLowerCase();
      return (
        task.title.toLowerCase().includes(searchLower) ||
        (task.description &&
          task.description.toLowerCase().includes(searchLower))
      );
    })
    .map((task) => {
      // Calculer la pertinence de la recherche pour chaque tâche
      const searchLower = taskSearch.toLowerCase();
      const titleMatch = task.title.toLowerCase().includes(searchLower);
      const descriptionMatch =
        task.description?.toLowerCase().includes(searchLower) || false;

      return {
        task,
        // Score de pertinence : match dans titre = 2, match dans description = 1
        relevanceScore: titleMatch ? 2 : descriptionMatch ? 1 : 0,
      };
    })
    .sort((a, b) => {
      const { task: taskA, relevanceScore: relevanceA } = a;
      const { task: taskB, relevanceScore: relevanceB } = b;

      // 1. Prioriser les tâches non terminées (même si elles apparaissent plus tard dans la recherche)
      const aCompleted = isCompletedStatus(taskA.status);
      const bCompleted = isCompletedStatus(taskB.status);

      if (aCompleted && !bCompleted) return 1;
      if (!aCompleted && bCompleted) return -1;

      // 2. Si même statut de complétion, trier par ordre de statut (in_progress avant todo, etc.)
      if (!aCompleted && !bCompleted) {
        const statusA = getStatusConfig(taskA.status as TaskStatus);
        const statusB = getStatusConfig(taskB.status as TaskStatus);
        const statusDiff = statusB.order - statusA.order; // Ordre décroissant (in_progress=2 avant todo=1)
        if (statusDiff !== 0) return statusDiff;
      }

      // 3. Prioriser les matches dans le titre vs la description
      if (relevanceA !== relevanceB) {
        return relevanceB - relevanceA; // Score décroissant
      }

      // 4. Enfin, trier par titre alphabétique
      return taskA.title.localeCompare(taskB.title);
    })
    .map(({ task }) => task); // Extraire les tâches du mapping

  const handleTaskSelect = (task: Task) => {
    setTaskId(task.id);
    setTaskSearch(''); // Fermer la recherche après sélection
  };

  const handleSave = async () => {
    if (!text.trim()) return;

    try {
      await onSave(text.trim(), type, taskId, date);
      onClose();
    } catch (error) {
      console.error('Erreur lors de la sauvegarde:', error);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSave();
    }
  };

  const resetForm = () => {
    setText(checkbox.text);
    setType(checkbox.type);
    setTaskId(checkbox.taskId);
    setDate(checkbox.date);
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  return (
    <Modal isOpen={isOpen} onClose={handleClose} title="Modifier la tâche">
      <div className="space-y-4">
        {/* Texte */}
        <div>
          <label className="block text-sm font-medium text-[var(--foreground)] mb-2">
            Description
          </label>
          <Input
            value={text}
            onChange={(e) => setText(e.target.value)}
            onKeyDown={handleKeyPress}
            placeholder="Description de la tâche..."
            className="w-full"
            autoFocus
          />
        </div>

        {/* Type */}
        <div>
          <label className="block text-sm font-medium text-[var(--foreground)] mb-2">
            Type
          </label>
          <div className="flex gap-2">
            <ToggleButton
              onClick={() => setType('meeting')}
              variant="primary"
              size="sm"
              isActive={type === 'meeting'}
              icon={<Calendar size={14} />}
            >
              <span className="text-sm">Réunion</span>
            </ToggleButton>
            <ToggleButton
              onClick={() => setType('task')}
              variant="primary"
              size="sm"
              isActive={type === 'task'}
              icon={<CheckSquare2 size={14} />}
            >
              <span className="text-sm">Tâche</span>
            </ToggleButton>
          </div>
        </div>

        {/* Date/Heure */}
        <div>
          <label className="block text-sm font-medium text-[var(--foreground)] mb-2">
            Date/Heure
          </label>
          <DateTimeInput
            value={date}
            onChange={(newDate) => newDate && setDate(newDate)}
            disabled={saving}
          />
        </div>

        {/* Liaison tâche (pour tous les types) */}
        <div>
          <label className="block text-sm font-medium text-[var(--foreground)] mb-2">
            Lier à une tâche (optionnel)
          </label>

          {selectedTask ? (
            // Tâche déjà sélectionnée
            <Card className="p-4" background="muted" shadow="sm">
              <div className="flex items-start justify-between gap-3">
                <div className="flex-1 min-w-0">
                  <div className="font-medium text-sm text-[var(--foreground)] truncate mb-1.5">
                    {selectedTask.title}
                  </div>
                  {selectedTask.description && (
                    <div className="text-xs text-[var(--muted-foreground)] truncate mb-2">
                      {selectedTask.description}
                    </div>
                  )}
                  <div className="flex items-center gap-2 flex-wrap">
                    <StatusBadge status={selectedTask.status} />
                    {selectedTask.tags && selectedTask.tags.length > 0 && (
                      <TagDisplay
                        tags={selectedTask.tags}
                        size="sm"
                        availableTags={selectedTask.tagDetails}
                        maxTags={3}
                      />
                    )}
                  </div>
                </div>
                <Button
                  type="button"
                  onClick={() => setTaskId(undefined)}
                  variant="ghost"
                  size="sm"
                  className="text-[var(--destructive)] hover:bg-[color-mix(in_srgb,var(--destructive)_10%,transparent)] flex-shrink-0"
                  disabled={saving}
                >
                  ×
                </Button>
              </div>
            </Card>
          ) : (
            // Interface de sélection simplifiée
            <div className="space-y-2">
              <SearchInput
                value={taskSearch}
                onChange={setTaskSearch}
                placeholder="Rechercher une tâche..."
                disabled={saving || tasksLoading}
                className="w-full"
              />

              {taskSearch.trim() && (
                <Card
                  className="max-h-64 overflow-y-auto"
                  shadow="sm"
                  background="default"
                >
                  {tasksLoading ? (
                    <div className="p-4 text-center text-sm text-[var(--muted-foreground)]">
                      Chargement...
                    </div>
                  ) : filteredTasks.length === 0 ? (
                    <div className="p-4 text-center text-sm text-[var(--muted-foreground)]">
                      Aucune tâche trouvée
                    </div>
                  ) : (
                    <div>
                      {filteredTasks.slice(0, 8).map((task, index) => {
                        const isCompleted = isCompletedStatus(task.status);
                        return (
                          <div key={task.id}>
                            {index > 0 && (
                              <div className="h-px bg-[color-mix(in_srgb,var(--border)_10%,transparent)]" />
                            )}
                            <button
                              type="button"
                              onClick={() => handleTaskSelect(task)}
                              className={`
                                w-full text-left p-3 transition-all duration-200
                                hover:bg-[color-mix(in_srgb,var(--primary)_8%,transparent)]
                                active:bg-[color-mix(in_srgb,var(--primary)_12%,transparent)]
                                disabled:opacity-50 disabled:cursor-not-allowed
                                focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/20 focus-visible:ring-inset
                                ${isCompleted ? 'opacity-60' : 'opacity-100'}
                              `}
                              disabled={saving}
                            >
                              <div
                                className={`
                              font-medium text-sm truncate
                              ${isCompleted ? 'text-[var(--muted-foreground)]' : 'text-[var(--foreground)]'}
                            `}
                              >
                                {task.title}
                              </div>
                              {task.description && (
                                <div
                                  className={`
                                text-xs truncate mt-1.5 max-w-full overflow-hidden
                                ${isCompleted ? 'text-[var(--muted-foreground)]/70' : 'text-[var(--muted-foreground)]'}
                              `}
                                >
                                  {task.description}
                                </div>
                              )}
                              <div className="flex items-center gap-2 mt-2 flex-wrap">
                                <StatusBadge
                                  status={task.status}
                                  className={isCompleted ? 'opacity-70' : ''}
                                />
                                {task.tags && task.tags.length > 0 && (
                                  <TagDisplay
                                    tags={task.tags}
                                    size="sm"
                                    availableTags={task.tagDetails}
                                    maxTags={3}
                                  />
                                )}
                              </div>
                            </button>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </Card>
              )}
            </div>
          )}
        </div>

        {/* Actions */}
        <div className="flex gap-2 justify-end pt-4">
          <Button
            type="button"
            onClick={handleClose}
            variant="ghost"
            disabled={saving}
          >
            Annuler
          </Button>
          <Button
            type="button"
            onClick={handleSave}
            variant="primary"
            disabled={!text.trim() || saving}
          >
            {saving ? 'Sauvegarde...' : 'Sauvegarder'}
          </Button>
        </div>
      </div>
    </Modal>
  );
}
