import type { UserTablo } from "@xtablo/shared/types/tablos.types";
import type { Etape, TaskStatus } from "@xtablo/shared-types";
import { Button } from "@xtablo/ui/components/button";
import { DatePicker } from "@xtablo/ui/components/date-picker";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@xtablo/ui/components/select";
import { Textarea } from "@xtablo/ui/components/textarea";
import { TypographyH2 } from "@xtablo/ui/components/typography";
import { X } from "lucide-react";
import { useEffect, useState } from "react";
import { useTabloMembers } from "../../hooks/tablos";
import { useCreateTask, useTabloEtapes, useTask, useUpdateTask } from "../../hooks/tasks";
import type { TabloMember } from "./types";

interface TaskModalProps {
  isOpen: boolean;
  tabloId?: string; // Optional when creating a task - can select tablo
  taskId?: string | undefined; // Optional - undefined when creating new task
  onClose: () => void;
  members?: TabloMember[]; // Optional - will be fetched if tabloId is provided
  initialStatus?: TaskStatus;
  etapes?: Etape[]; // Optional - will be fetched if tabloId is provided
  tablos?: UserTablo[]; // Optional - for tablo selection when creating
  allowTabloSelection?: boolean; // Whether to show tablo selector
  initialDueDate?: Date;
}

export const TaskModal = ({
  tabloId: initialTabloId,
  taskId,
  isOpen,
  onClose,
  members: providedMembers,
  initialStatus = "todo",
  etapes: providedEtapes,
  tablos,
  allowTabloSelection = false,
  initialDueDate,
}: TaskModalProps) => {
  const { data: task = null } = useTask(taskId);
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [assigneeId, setAssigneeId] = useState<string>("unassigned");
  const [etapeId, setEtapeId] = useState<string>("none");
  const [dueDate, setDueDate] = useState<Date | undefined>(undefined);
  const [selectedTabloId, setSelectedTabloId] = useState<string>(
    initialTabloId || tablos?.[0]?.id || ""
  );

  // Determine which tablo to use for fetching data
  const tabloIdForFetch = allowTabloSelection ? selectedTabloId : initialTabloId || "";

  // Fetch members and etapes for selected tablo if not provided
  const { data: fetchedMembers = [] } = useTabloMembers(tabloIdForFetch || "");
  const { data: fetchedEtapes = [] } = useTabloEtapes(tabloIdForFetch || undefined);

  // Use provided or fetched data
  const members = providedMembers || fetchedMembers;
  const etapes = providedEtapes || fetchedEtapes;
  const currentTabloId = allowTabloSelection ? selectedTabloId : initialTabloId || "";

  useEffect(() => {
    if (task) {
      setTitle(task.title ?? "");
      setDescription(task.description ?? "");
      setAssigneeId(task.assignee_id ?? "unassigned");
      setEtapeId(task.parent_task_id ?? "none");
      setDueDate(task.due_date ? new Date(task.due_date) : undefined);
      if (!initialTabloId && task.tablo_id) {
        setSelectedTabloId(task.tablo_id);
      }
    } else {
      // Reset form when creating new task
      setTitle("");
      setDescription("");
      setAssigneeId("unassigned");
      setEtapeId("none");
      setDueDate(initialDueDate ? new Date(initialDueDate) : undefined);
      if (allowTabloSelection && tablos && tablos.length > 0) {
        setSelectedTabloId(tablos[0].id);
      }
    }
  }, [task, initialTabloId, allowTabloSelection, tablos, initialDueDate]);

  const { mutate: createTask } = useCreateTask();
  const { mutate: updateTask } = useUpdateTask();

  // Format Date to YYYY-MM-DD string for database storage
  const formatDateForDb = (date: Date | undefined): string | null => {
    if (!date) return null;
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim()) return;
    if (!currentTabloId) return; // Need a tablo to create task

    const dueDateValue = formatDateForDb(dueDate);

    if (taskId && task) {
      updateTask({
        tablo_id: task.tablo_id,
        id: task.id,
        title: title.trim(),
        description: description.trim(),
        assignee_id: assigneeId !== "unassigned" ? assigneeId : undefined,
        status: initialStatus,
        parent_task_id: etapeId !== "none" ? etapeId : null,
        due_date: dueDateValue,
      });
    } else {
      createTask({
        tablo_id: currentTabloId,
        title: title.trim(),
        description: description.trim(),
        assignee_id: assigneeId !== "unassigned" ? assigneeId : undefined,
        status: initialStatus,
        parent_task_id: etapeId !== "none" ? etapeId : null,
        due_date: dueDateValue,
      });
    }
    // Reset form
    setTitle("");
    setDescription("");
    setAssigneeId("unassigned");
    setEtapeId("none");
    setDueDate(undefined);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-card border border-border rounded-lg p-6 w-full max-w-md shadow-xl">
        {/* Header */}
        <div className="flex items-center justify-between mb-4">
          <TypographyH2 className="text-xl font-bold text-foreground">
            {taskId ? "Modifier la tâche" : "Créer une tâche"}
          </TypographyH2>
          <button
            onClick={onClose}
            className="text-muted-foreground hover:text-foreground transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Tablo Selection - only show when creating and allowTabloSelection is true */}
          {allowTabloSelection && !taskId && tablos && tablos.length > 0 && (
            <div className="space-y-2">
              <Label htmlFor="tablo">Tablo *</Label>
              <Select value={selectedTabloId} onValueChange={setSelectedTabloId}>
                <SelectTrigger id="tablo" className="w-full">
                  <SelectValue placeholder="Sélectionner un tablo" />
                </SelectTrigger>
                <SelectContent>
                  {tablos.map((tablo) => (
                    <SelectItem key={tablo.id} value={tablo.id}>
                      <div className="flex items-center gap-2">
                        <div
                          className={`w-2 h-2 rounded-full ${tablo.color || "bg-muted-foreground"}`}
                        />
                        {tablo.name}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          {/* Title */}
          <div className="space-y-2">
            <Label htmlFor="title">Titre *</Label>
            <Input
              id="title"
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Titre de la tâche"
              required
            />
          </div>

          {/* Description */}
          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Textarea
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Description de la tâche"
              className="min-h-[100px]"
            />
          </div>

          {/* Due Date */}
          <div className="space-y-2">
            <Label>Échéance</Label>
            <DatePicker value={dueDate} onChange={setDueDate} placeholder="Choisir une date" />
          </div>

          {/* Assignee */}
          <div className="space-y-2">
            <Label htmlFor="assignee">Assigné à</Label>
            <Select value={assigneeId} onValueChange={setAssigneeId}>
              <SelectTrigger id="assignee" className="w-full">
                <SelectValue placeholder="Non assigné" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="unassigned">Non assigné</SelectItem>
                {members.map((member) => (
                  <SelectItem key={member.id} value={member.id}>
                    {member.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Étape */}
          {etapes.length > 0 && (
            <div className="space-y-2">
              <Label htmlFor="etape">Étape</Label>
              <Select value={etapeId} onValueChange={setEtapeId}>
                <SelectTrigger id="etape" className="w-full">
                  <SelectValue placeholder="Aucune Étape" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">Aucune</SelectItem>
                  {etapes.map((etape) => (
                    <SelectItem key={etape.id} value={etape.id}>
                      {etape.title}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          {/* Actions */}
          <div className="flex justify-end gap-2 pt-4">
            <Button type="button" variant="ghost" onClick={onClose}>
              Annuler
            </Button>
            <Button type="submit">{taskId ? "Modifier" : "Créer"}</Button>
          </div>
        </form>
      </div>
    </div>
  );
};
