'use client';

import { useState, useEffect } from 'react';
import { Modal } from '@/components/ui/Modal';
import { Button } from '@/components/ui/Button';
import { Task, TaskPriority, TaskStatus } from '@/lib/types';
import { TaskBasicFields } from './task/TaskBasicFields';
import { TaskJiraInfo } from './task/TaskJiraInfo';
import { TaskTfsInfo } from './task/TaskTfsInfo';
import { TaskTagsSection } from './task/TaskTagsSection';

interface EditTaskFormProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (data: {
    taskId: string;
    title?: string;
    description?: string;
    status?: TaskStatus;
    priority?: TaskPriority;
    tags?: string[];
    primaryTagId?: string;
    dueDate?: Date;
  }) => Promise<void>;
  task: Task | null;
  loading?: boolean;
}

export function EditTaskForm({
  isOpen,
  onClose,
  onSubmit,
  task,
  loading = false,
}: EditTaskFormProps) {
  const [formData, setFormData] = useState<{
    title: string;
    description: string;
    status: TaskStatus;
    priority: TaskPriority;
    tags: string[];
    primaryTagId?: string;
    dueDate?: Date;
  }>({
    title: '',
    description: '',
    status: 'todo' as TaskStatus,
    priority: 'medium' as TaskPriority,
    tags: [],
    primaryTagId: undefined,
    dueDate: undefined,
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  // Pré-remplir le formulaire quand la tâche change
  useEffect(() => {
    if (task) {
      setFormData({
        title: task.title,
        description: task.description || '',
        status: task.status,
        priority: task.priority,
        tags: task.tags || [],
        primaryTagId: task.primaryTagId,
        dueDate: task.dueDate,
      });
    }
  }, [task]);

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.title?.trim()) {
      newErrors.title = 'Le titre est requis';
    }

    if (formData.title && formData.title.length > 200) {
      newErrors.title = 'Le titre ne peut pas dépasser 200 caractères';
    }

    if (formData.description && formData.description.length > 1000) {
      newErrors.description =
        'La description ne peut pas dépasser 1000 caractères';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

    if (!validateForm() || !task) return;

    try {
      await onSubmit({
        taskId: task.id,
        ...formData,
      });
      handleClose();
    } catch (error) {
      console.error('Erreur lors de la mise à jour:', error);
    }
  };

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

  if (!task) return null;

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleClose}
      title="Modifier la tâche"
      size="lg"
    >
      <form
        onSubmit={handleSubmit}
        className="space-y-4 max-h-[80vh] overflow-y-auto pr-2"
      >
        <TaskBasicFields
          title={formData.title}
          description={formData.description}
          priority={formData.priority}
          status={formData.status}
          dueDate={formData.dueDate}
          onTitleChange={(title) => setFormData((prev) => ({ ...prev, title }))}
          onDescriptionChange={(description) =>
            setFormData((prev) => ({ ...prev, description }))
          }
          onPriorityChange={(priority) =>
            setFormData((prev) => ({ ...prev, priority }))
          }
          onStatusChange={(status) =>
            setFormData((prev) => ({ ...prev, status }))
          }
          onDueDateChange={(dueDate) =>
            setFormData((prev) => ({ ...prev, dueDate }))
          }
          errors={errors}
          loading={loading}
          readonlyFields={task.readonlyFields || []}
          source={task.source}
        />

        <TaskJiraInfo task={task} />

        <TaskTfsInfo task={task} />

        <TaskTagsSection
          taskId={task.id}
          tags={formData.tags}
          primaryTagId={formData.primaryTagId}
          onTagsChange={(tags) => setFormData((prev) => ({ ...prev, tags }))}
          onPrimaryTagChange={(primaryTagId) =>
            setFormData((prev) => ({ ...prev, primaryTagId }))
          }
        />

        {/* Actions */}
        <div className="flex justify-end gap-3 pt-4 border-t border-[var(--border)]/50">
          <Button
            type="button"
            variant="ghost"
            onClick={handleClose}
            disabled={loading}
          >
            Annuler
          </Button>
          <Button type="submit" variant="primary" disabled={loading}>
            {loading ? 'Mise à jour...' : 'Mettre à jour'}
          </Button>
        </div>
      </form>
    </Modal>
  );
}
