'use client';

import React, { useState, useEffect, ChangeEvent } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Task, Client, TaskStatus } from '@/types/types';
import { format } from 'date-fns';
import { useTask } from '@/hooks/useTask';
import { getClients } from '@/helpers/axios_helper';

interface TaskFormProps {
  task?: Task; // Optional, for editing existing tasks
  onSuccess: () => void;
  isAutomatic?: boolean;
  clientId?: number | null;
  folderId?: number | null;
  currentUserId: number;
  currentUserName: string;
}

export default function TaskForm({
  task,
  onSuccess,
  isAutomatic = false,
  clientId: defaultClientId = null,
  folderId: defaultFolderId = null,
  currentUserId,
  currentUserName,
}: TaskFormProps) {
  const router = useRouter();
  const { data: session } = useSession();
  const [formData, setFormData] = useState<Partial<Task>>({
    title: '',
    description: null,
    startDate: new Date(),
    dueDate: null,
    status: TaskStatus.PENDING,
    priority: null,
    isAutomatic: isAutomatic,
    completedAt: null,
    duration: null,
    appreciation: null,
    responsibleId: currentUserId,
    clientId: defaultClientId,
    folderId: defaultFolderId,
    isPrivate: false, // Default to false
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [clients, setClients] = useState<Client[]>([]);
  const [clientsLoading, setClientsLoading] = useState(true);
  const [clientsError, setClientsError] = useState<string | null>(null);

  const { createTask, updateTask } = useTask({
    onSuccess,
    onError: (err) => setError(err.response?.data?.message || 'An error occurred during save'),
  });

  // Récupérer la liste des clients
  useEffect(() => {
    const fetchClients = async () => {
      setClientsLoading(true);
      setClientsError(null);
      try {
        console.log('Fetching clients...');
        const clientsData = await getClients();
        console.log('Clients fetched:', clientsData);
        console.log('Number of clients:', clientsData.length);
        setClients(clientsData);
      } catch (err) {
        console.error('Error fetching clients:', err);
        setClientsError('Erreur lors du chargement des clients');
      } finally {
        setClientsLoading(false);
      }
    };
    fetchClients();
  }, []);

  useEffect(() => {
    if (task) {
      setFormData({
        ...task,
        startDate: task.startDate ? new Date(task.startDate) : null,
        dueDate: task.dueDate ? new Date(task.dueDate) : null,
        completedAt: task.completedAt ? new Date(task.completedAt) : null,
        // Ensure responsibleId is a number
        responsibleId: task.responsibleId,
        // Ensure optional relations are null if not present
        clientId: task.clientId || null,
        folderId: task.folderId || null,
        priority: task.priority || null,
        description: task.description || null,
        duration: task.duration || null,
        appreciation: task.appreciation || null,
        isPrivate: task.isPrivate || false,
      });
    }
  }, [task]);

  const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target;

    let newValue: any = value;
    if (type === 'checkbox') {
      newValue = (e.target as HTMLInputElement).checked; // Explicitly cast to HTMLInputElement
    } else if (name === 'startDate' || name === 'dueDate') {
      newValue = value ? new Date(value) : null; // Explicitly null for empty date
    } else if (value === '') {
      newValue = null; // Convert empty string to null for optional string fields
    }

    setFormData(prev => ({ ...prev, [name]: newValue }));
  };

  const handleSelectChange = (name: keyof Partial<Task>, value: string | TaskStatus) => {
    setFormData((prev) => ({
      ...prev,
      [name]: value === 'none' ? null : value,
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validation : client obligatoire
    if (!formData.clientId) {
      setError('Veuillez sélectionner un client pour cette tâche');
      return;
    }
    
    setLoading(true);
    setError(null);

    try {
      const payload = { ...formData };

      // Clean up payload: ensure optional string fields are null if empty string
      for (const key of ['description', 'priority', 'duration', 'appreciation'] as (keyof Task)[]) {
        if (typeof payload[key] === 'string' && payload[key] === '') {
          (payload[key] as any) = null;
        }
      }

      // Convert dates to ISO strings before sending to API
      if (payload.startDate) payload.startDate = payload.startDate.toISOString() as any;
      if (payload.dueDate) payload.dueDate = payload.dueDate.toISOString() as any;
      if (payload.completedAt) payload.completedAt = payload.completedAt.toISOString() as any;

      // Ensure responsibleId is set from current user for new tasks if not already present
      if (!payload.id && !payload.responsibleId) {
        payload.responsibleId = currentUserId;
      }

      // The status logic is now primarily handled by the API/useTask hook on creation/update
      console.log('🔍 TaskForm - User role:', (session?.user as any)?.role);
      console.log('🔍 TaskForm - Payload being sent:', payload);

      if (task?.id) {
        await updateTask(task.id, payload);
      } else {
        await createTask(payload);
      }
    } catch (err: any) {
      console.error('Error saving task:', err);
      setError(err.response?.data?.message || 'Error saving task');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto p-4">
      <h2 className="text-2xl font-bold mb-6">
        {task ? 'Modifier la Tâche' : 'Nouvelle Tâche'}
      </h2>

      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4">
          {error}
        </div>
      )}

      {/* Debug info pour les clients */}
      {/* (Retiré car plus nécessaire) */}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <Label htmlFor="title">Titre de la tâche</Label>
          <Input
            type="text"
            id="title"
            name="title"
            value={formData.title || ''}
            onChange={handleChange}
            required
          />
        </div>

        <div>
          <Label htmlFor="description">Description</Label>
          <Textarea
            id="description"
            name="description"
            value={formData.description || ''}
            onChange={handleChange}
            rows={4}
          />
        </div>

        <div>
          <Label htmlFor="startDate">Date de début</Label>
          <Input
            type="date"
            id="startDate"
            name="startDate"
            value={formData.startDate ? format(new Date(formData.startDate), 'yyyy-MM-dd') : ''}
            onChange={handleChange}
            required
          />
        </div>

        <div>
          <Label htmlFor="dueDate">Date d'échéance</Label>
          <Input
            type="date"
            id="dueDate"
            name="dueDate"
            value={formData.dueDate ? format(new Date(formData.dueDate), 'yyyy-MM-dd') : ''}
            onChange={handleChange}
          />
        </div>

        {/* Client field - remplace le champ responsable */}
        {defaultClientId == null ? (
          <div>
            <Label htmlFor="clientId">Client * ({clients.length} clients disponibles)</Label>
            <select
              id="clientId"
              name="clientId"
              value={formData.clientId?.toString() ?? ''}
              onChange={(e) => {
                const value = e.target.value;
                handleSelectChange('clientId', value);
              }}
              className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            >
              <option value="">Sélectionner un client (obligatoire)</option>
              {clients.map(client => (
                <option key={client.id} value={client.id.toString()}>
                  {`${client.firstName} ${client.lastName}`}
                </option>
              ))}
            </select>
            {!formData.clientId && (
              <p className="text-sm text-red-500 mt-1">
                ⚠️ Veuillez sélectionner un client
              </p>
            )}
          </div>
        ) : (
          <div>
            <Label>Client</Label>
            <input
              type="text"
              value={
                clients.find(c => c.id === defaultClientId)?.firstName + ' ' + clients.find(c => c.id === defaultClientId)?.lastName || 'Client inconnu'
              }
              disabled
              className="w-full p-2 border border-gray-300 rounded-md bg-gray-100 text-gray-500"
            />
            <input type="hidden" name="clientId" value={defaultClientId} />
          </div>
        )}

        {/* Priority field */}
        <div>
          <Label htmlFor="priority">Priorité *</Label>
          <select
            id="priority"
            name="priority"
            value={formData.priority ?? ''}
            onChange={e => handleSelectChange('priority', e.target.value)}
            className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          >
            <option value="">Sélectionner une priorité (obligatoire)</option>
            <option value="faible">🔵 Faible</option>
            <option value="moyen">🟡 Moyen</option>
            <option value="urgent">🔴 Urgent</option>
          </select>
          {!formData.priority && (
            <p className="text-sm text-red-500 mt-1">
              ⚠️ Veuillez sélectionner une priorité
            </p>
          )}
        </div>

        {/* Status field (only for editing, or if automatic task logic changes it) */}
        {task && (
          <div>
            <Label htmlFor="status">Statut</Label>
            <Select onValueChange={(value: TaskStatus) => handleSelectChange('status', value)} value={formData.status ?? TaskStatus.PENDING}>
              <SelectTrigger>
                <SelectValue placeholder="Sélectionner un statut" />
              </SelectTrigger>
              <SelectContent>
                {Object.values(TaskStatus).map(status => (
                  <SelectItem key={status} value={status}>
                    {status.replace(/_/g, ' ')}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}

        {/* isPrivate field */}
        <div>
          <Label htmlFor="isPrivate" className="flex items-center space-x-2">
            <Input
              type="checkbox"
              id="isPrivate"
              name="isPrivate"
              checked={formData.isPrivate || false}
              onChange={handleChange}
              className="h-4 w-4"
            />
            <span>Tâche privée</span>
          </Label>
        </div>

        {/* Hidden field for responsibleId */}
        <input type="hidden" name="responsibleId" value={currentUserId} />

        <Button 
          type="submit" 
          disabled={loading}
          className="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 active:scale-95 shadow-lg hover:shadow-xl"
        >
          {loading ? (
            <div className="flex items-center justify-center">
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
              Enregistrement...
            </div>
          ) : (
            'Enregistrer la Tâche'
          )}
        </Button>
      </form>
    </div>
  );
} 