import type { Etape, TaskStatus } from "@xtablo/shared-types";
import { Button } from "@xtablo/ui/components/button";
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 { Plus, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import type { TabloMember } from "./types";

interface InlineTaskCreateProps {
  status: TaskStatus;
  members: TabloMember[];
  etapes: Etape[];
  onSubmit: (task: {
    title: string;
    description: string;
    assignee_id?: string;
    status: TaskStatus;
    parent_task_id?: string | null;
  }) => void;
}

export const InlineTaskCreate = ({ status, members, etapes, onSubmit }: InlineTaskCreateProps) => {
  const [isCreating, setIsCreating] = useState(false);
  const [title, setTitle] = useState("");
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [description, setDescription] = useState("");
  const [assigneeId, setAssigneeId] = useState<string>("unassigned");
  const [etapeId, setEtapeId] = useState<string>("none");
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (isCreating && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isCreating]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim()) return;

    onSubmit({
      title: title.trim(),
      description: description.trim(),
      assignee_id: assigneeId !== "unassigned" ? assigneeId : undefined,
      status,
      parent_task_id: etapeId !== "none" ? etapeId : undefined,
    });

    // Reset form
    setTitle("");
    setDescription("");
    setAssigneeId("unassigned");
    setEtapeId("none");
    setShowAdvanced(false);
    setIsCreating(false);
  };

  const handleCancel = () => {
    setTitle("");
    setDescription("");
    setAssigneeId("unassigned");
    setShowAdvanced(false);
    setIsCreating(false);
  };

  if (!isCreating) {
    return (
      <button
        onClick={() => setIsCreating(true)}
        className="w-full flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-muted/50 rounded-lg transition-colors"
      >
        <Plus className="w-4 h-4" />
        Ajouter une tâche
      </button>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="bg-card border border-border rounded-lg p-3 space-y-2">
      {/* Title Input */}
      <Input
        ref={inputRef}
        type="text"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        placeholder="Titre de la tâche..."
        className="text-sm"
        required
      />

      {etapes.length > 0 && (
        <div className="space-y-1">
          <Label htmlFor={`etape-${status}`} className="text-xs text-muted-foreground">
            Étape
          </Label>
          <Select value={etapeId} onValueChange={setEtapeId}>
            <SelectTrigger id={`etape-${status}`} size="sm" className="w-full text-sm h-8">
              <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>
      )}

      {/* Advanced Options */}
      {showAdvanced && (
        <div className="space-y-2 pt-2 border-t border-border">
          {/* Description */}
          <Textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Description (optionnel)"
            className="text-sm min-h-[60px]"
          />

          {/* Type and Assignee */}
          <div className="grid grid-cols-2 gap-2">
            {/* <div className="space-y-1">
              <Label htmlFor="type" className="text-xs text-muted-foreground">
                Type
              </Label>
              <Select value={type} onValueChange={(value) => setType(value as TaskType)}>
                <SelectTrigger id="type" size="sm" className="w-full text-sm h-8">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="task">Task</SelectItem>
                  <SelectItem value="story">Story</SelectItem>
                  <SelectItem value="bug">Bug</SelectItem>
                  <SelectItem value="epic">Epic</SelectItem>
                  <SelectItem value="subtask">Subtask</SelectItem>
                </SelectContent>
              </Select>
            </div> */}

            <div className="space-y-1">
              <Label htmlFor="assignee" className="text-xs text-muted-foreground">
                Assigné à
              </Label>
              <Select value={assigneeId} onValueChange={setAssigneeId}>
                <SelectTrigger id="assignee" size="sm" className="w-full text-sm h-8">
                  <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>
          </div>
        </div>
      )}

      {/* Actions */}
      <div className="flex items-center justify-between gap-1 pt-1">
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={() => setShowAdvanced(!showAdvanced)}
          className="text-xs h-7 px-2"
        >
          {showAdvanced ? "Moins d'options" : "Plus d'options"}
        </Button>

        <div className="flex items-center gap-1">
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={handleCancel}
            className="h-7 w-7 p-0"
          >
            <X className="w-3 h-3" />
          </Button>
          <Button type="submit" size="sm" className="h-7 px-2 text-xs">
            Ajouter
          </Button>
        </div>
      </div>
    </form>
  );
};
