import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, Search, X, Check, Trash2, ChevronRight } from "lucide-react";
import { MOCK_TASKS, MOCK_SUBTASKS, MOCK_USERS, type MockTask, type MockSubtask, type TaskStatus, type TaskPriority } from "@/data/mockData";
import { StatusBadge } from "@/components/shared/StatusBadge";
import { PriorityBadge } from "@/components/shared/PriorityBadge";

const STATUSES: TaskStatus[] = ["pending", "in_progress", "completed"];
const PRIORITIES: TaskPriority[] = ["high", "medium", "low"];

export default function TasksPage() {
  const [tasks, setTasks] = useState(MOCK_TASKS);
  const [subtasks, setSubtasks] = useState(MOCK_SUBTASKS);
  const [search, setSearch] = useState("");
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [filterPriority, setFilterPriority] = useState<string>("all");
  const [selectedTask, setSelectedTask] = useState<MockTask | null>(null);
  const [showCreateTask, setShowCreateTask] = useState(false);
  const [showCreateSubtask, setShowCreateSubtask] = useState(false);
  const [newTask, setNewTask] = useState({ title: "", description: "", status: "pending" as TaskStatus, priority: "medium" as TaskPriority, assignedUserId: "", dueDate: "" });
  const [newSubtask, setNewSubtask] = useState({ title: "", status: "pending" as TaskStatus, priority: "medium" as TaskPriority });

  const filtered = tasks.filter(t => {
    const matchSearch = t.title.toLowerCase().includes(search.toLowerCase());
    const matchStatus = filterStatus === "all" || t.status === filterStatus;
    const matchPriority = filterPriority === "all" || t.priority === filterPriority;
    return matchSearch && matchStatus && matchPriority;
  });

  const taskSubtasks = selectedTask ? subtasks.filter(s => s.taskId === selectedTask.id) : [];

  const handleCreateTask = () => {
    if (!newTask.title.trim()) return;
    const task: MockTask = {
      id: tasks.length + 100,
      tenantId: 1,
      title: newTask.title,
      description: newTask.description,
      status: newTask.status,
      priority: newTask.priority,
      assignedUserId: newTask.assignedUserId ? parseInt(newTask.assignedUserId) : null,
      assignedUserName: newTask.assignedUserId ? MOCK_USERS.find(u => u.id === parseInt(newTask.assignedUserId))?.name ?? null : null,
      dueDate: newTask.dueDate || null,
      completionPercent: 0,
      subtaskCount: 0,
      completedSubtaskCount: 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    setTasks(prev => [task, ...prev]);
    setNewTask({ title: "", description: "", status: "pending", priority: "medium", assignedUserId: "", dueDate: "" });
    setShowCreateTask(false);
  };

  const handleToggleSubtask = (subtaskId: number) => {
    setSubtasks(prev => prev.map(s => s.id === subtaskId ? { ...s, status: s.status === "completed" ? "pending" : "completed" } : s));
  };

  const handleCreateSubtask = () => {
    if (!newSubtask.title.trim() || !selectedTask) return;
    const st: MockSubtask = {
      id: subtasks.length + 200,
      taskId: selectedTask.id,
      title: newSubtask.title,
      status: newSubtask.status,
      priority: newSubtask.priority,
      assignedUserId: null,
      assignedUserName: null,
      dueDate: null,
    };
    setSubtasks(prev => [...prev, st]);
    setNewSubtask({ title: "", status: "pending", priority: "medium" });
    setShowCreateSubtask(false);
  };

  const handleDeleteTask = (taskId: number) => {
    setTasks(prev => prev.filter(t => t.id !== taskId));
    if (selectedTask?.id === taskId) setSelectedTask(null);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Tasks</h1>
          <p className="text-sm text-muted-foreground mt-1">{filtered.length} of {tasks.length} tasks</p>
        </div>
        <button
          onClick={() => setShowCreateTask(true)}
          data-testid="button-create-task"
          className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg text-sm font-medium hover:bg-primary/90 transition"
        >
          <Plus className="w-4 h-4" /> New Task
        </button>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-3 items-center">
        <div className="relative flex-1 min-w-48">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Search tasks..."
            className="w-full pl-9 pr-4 py-2 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
          />
        </div>
        <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
          className="px-3 py-2 border border-border rounded-lg text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30"
        >
          <option value="all">All Status</option>
          {STATUSES.map(s => <option key={s} value={s}>{s.replace("_", " ")}</option>)}
        </select>
        <select value={filterPriority} onChange={e => setFilterPriority(e.target.value)}
          className="px-3 py-2 border border-border rounded-lg text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary/30"
        >
          <option value="all">All Priority</option>
          {PRIORITIES.map(p => <option key={p} value={p}>{p}</option>)}
        </select>
      </div>

      <div className="flex gap-6">
        {/* Task list */}
        <div className={`${selectedTask ? "w-1/2" : "w-full"} transition-all duration-300`}>
          <div className="bg-card border border-card-border rounded-xl shadow-sm overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border bg-muted/30">
                  <th className="text-left px-5 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Task</th>
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Status</th>
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Priority</th>
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden lg:table-cell">Assignee</th>
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden xl:table-cell">Progress</th>
                  <th className="px-4 py-3" />
                </tr>
              </thead>
              <tbody>
                {filtered.map((task, i) => (
                  <motion.tr
                    key={task.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: i * 0.04 }}
                    onClick={() => setSelectedTask(selectedTask?.id === task.id ? null : task)}
                    className={`border-b border-border/50 cursor-pointer transition-colors ${selectedTask?.id === task.id ? "bg-accent/60" : "hover:bg-muted/40"}`}
                    data-testid={`row-task-${task.id}`}
                  >
                    <td className="px-5 py-3.5">
                      <div>
                        <p className="font-medium text-foreground leading-snug">{task.title}</p>
                        <p className="text-xs text-muted-foreground mt-0.5">{task.subtaskCount} subtasks</p>
                      </div>
                    </td>
                    <td className="px-4 py-3.5"><StatusBadge status={task.status} /></td>
                    <td className="px-4 py-3.5"><PriorityBadge priority={task.priority} /></td>
                    <td className="px-4 py-3.5 hidden lg:table-cell">
                      <span className="text-xs text-muted-foreground">{task.assignedUserName ?? "—"}</span>
                    </td>
                    <td className="px-4 py-3.5 hidden xl:table-cell">
                      <div className="flex items-center gap-2 w-28">
                        <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
                          <div className="h-full bg-blue-500 rounded-full" style={{ width: `${task.completionPercent}%` }} />
                        </div>
                        <span className="text-xs text-muted-foreground">{task.completionPercent}%</span>
                      </div>
                    </td>
                    <td className="px-4 py-3.5">
                      <div className="flex items-center gap-1" onClick={e => e.stopPropagation()}>
                        <button onClick={() => handleDeleteTask(task.id)} className="p-1.5 hover:text-rose-500 text-muted-foreground rounded transition">
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                        <ChevronRight className="w-4 h-4 text-muted-foreground" />
                      </div>
                    </td>
                  </motion.tr>
                ))}
                {filtered.length === 0 && (
                  <tr><td colSpan={6} className="px-5 py-12 text-center text-muted-foreground text-sm">No tasks found</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Subtask panel */}
        <AnimatePresence>
          {selectedTask && (
            <motion.div
              initial={{ opacity: 0, x: 24 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: 24 }}
              transition={{ duration: 0.25 }}
              className="w-1/2 bg-card border border-card-border rounded-xl shadow-sm overflow-hidden flex flex-col"
            >
              <div className="px-5 py-4 border-b border-border flex items-start justify-between">
                <div className="flex-1">
                  <h3 className="font-semibold text-foreground leading-snug">{selectedTask.title}</h3>
                  <div className="flex gap-2 mt-2">
                    <StatusBadge status={selectedTask.status} />
                    <PriorityBadge priority={selectedTask.priority} />
                  </div>
                </div>
                <button onClick={() => setSelectedTask(null)} className="p-1.5 hover:bg-muted rounded text-muted-foreground">
                  <X className="w-4 h-4" />
                </button>
              </div>

              {selectedTask.description && (
                <p className="px-5 py-3 text-sm text-muted-foreground border-b border-border">{selectedTask.description}</p>
              )}

              <div className="flex-1 overflow-auto p-5">
                <div className="flex items-center justify-between mb-3">
                  <h4 className="text-sm font-semibold text-foreground">Subtasks ({taskSubtasks.length})</h4>
                  <button
                    onClick={() => setShowCreateSubtask(true)}
                    className="flex items-center gap-1 text-xs text-blue-600 hover:text-blue-700 font-medium"
                  >
                    <Plus className="w-3.5 h-3.5" /> Add
                  </button>
                </div>

                <div className="space-y-2">
                  {taskSubtasks.map(st => (
                    <div key={st.id} className="flex items-center gap-3 p-2.5 bg-muted/30 rounded-lg border border-border/40">
                      <button
                        onClick={() => handleToggleSubtask(st.id)}
                        className={`w-5 h-5 rounded border-2 flex items-center justify-center flex-shrink-0 transition-all ${st.status === "completed" ? "bg-emerald-500 border-emerald-500" : "border-gray-300 hover:border-emerald-400"}`}
                      >
                        {st.status === "completed" && <Check className="w-3 h-3 text-white" strokeWidth={3} />}
                      </button>
                      <div className="flex-1 min-w-0">
                        <p className={`text-sm ${st.status === "completed" ? "line-through text-muted-foreground" : "text-foreground"}`}>{st.title}</p>
                        {st.assignedUserName && <p className="text-xs text-muted-foreground">{st.assignedUserName}</p>}
                      </div>
                      <PriorityBadge priority={st.priority} />
                    </div>
                  ))}
                  {taskSubtasks.length === 0 && (
                    <p className="text-sm text-muted-foreground text-center py-6">No subtasks yet</p>
                  )}
                </div>

                {showCreateSubtask && (
                  <div className="mt-4 p-3 bg-muted/30 rounded-lg border border-border space-y-2">
                    <input
                      autoFocus
                      value={newSubtask.title}
                      onChange={e => setNewSubtask(p => ({ ...p, title: e.target.value }))}
                      placeholder="Subtask title..."
                      className="w-full px-3 py-2 border border-border rounded-md text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                    />
                    <div className="flex gap-2">
                      <select value={newSubtask.status} onChange={e => setNewSubtask(p => ({ ...p, status: e.target.value as TaskStatus }))}
                        className="flex-1 px-2 py-1.5 border border-border rounded-md text-xs bg-card focus:outline-none"
                      >
                        {STATUSES.map(s => <option key={s} value={s}>{s.replace("_", " ")}</option>)}
                      </select>
                      <select value={newSubtask.priority} onChange={e => setNewSubtask(p => ({ ...p, priority: e.target.value as TaskPriority }))}
                        className="flex-1 px-2 py-1.5 border border-border rounded-md text-xs bg-card focus:outline-none"
                      >
                        {PRIORITIES.map(p => <option key={p} value={p}>{p}</option>)}
                      </select>
                    </div>
                    <div className="flex gap-2">
                      <button onClick={handleCreateSubtask} className="flex-1 py-1.5 bg-primary text-primary-foreground text-xs font-medium rounded-md">Add</button>
                      <button onClick={() => setShowCreateSubtask(false)} className="flex-1 py-1.5 bg-muted text-muted-foreground text-xs font-medium rounded-md">Cancel</button>
                    </div>
                  </div>
                )}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Create Task Modal */}
      <AnimatePresence>
        {showCreateTask && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
            onClick={() => setShowCreateTask(false)}
          >
            <motion.div
              initial={{ scale: 0.96, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.96, opacity: 0 }}
              onClick={e => e.stopPropagation()}
              className="bg-card rounded-2xl shadow-2xl w-full max-w-md overflow-hidden"
            >
              <div className="px-6 py-5 border-b border-border flex items-center justify-between">
                <h2 className="text-base font-semibold text-foreground">Create New Task</h2>
                <button onClick={() => setShowCreateTask(false)} className="p-1.5 hover:bg-muted rounded text-muted-foreground"><X className="w-4 h-4" /></button>
              </div>
              <div className="p-6 space-y-4">
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Title *</label>
                  <input value={newTask.title} onChange={e => setNewTask(p => ({ ...p, title: e.target.value }))}
                    placeholder="Enter task title..."
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Description</label>
                  <textarea value={newTask.description} onChange={e => setNewTask(p => ({ ...p, description: e.target.value }))}
                    placeholder="Optional description..."
                    rows={3}
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30 resize-none"
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Status</label>
                    <select value={newTask.status} onChange={e => setNewTask(p => ({ ...p, status: e.target.value as TaskStatus }))}
                      className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                    >
                      {STATUSES.map(s => <option key={s} value={s}>{s.replace("_", " ")}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Priority</label>
                    <select value={newTask.priority} onChange={e => setNewTask(p => ({ ...p, priority: e.target.value as TaskPriority }))}
                      className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                    >
                      {PRIORITIES.map(p => <option key={p} value={p}>{p}</option>)}
                    </select>
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Assign to</label>
                    <select value={newTask.assignedUserId} onChange={e => setNewTask(p => ({ ...p, assignedUserId: e.target.value }))}
                      className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                    >
                      <option value="">Unassigned</option>
                      {MOCK_USERS.filter(u => u.status === "active").map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Due Date</label>
                    <input type="date" value={newTask.dueDate} onChange={e => setNewTask(p => ({ ...p, dueDate: e.target.value }))}
                      className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                    />
                  </div>
                </div>
                <div className="flex gap-3 pt-2">
                  <button onClick={() => setShowCreateTask(false)} className="flex-1 py-2.5 bg-muted text-muted-foreground text-sm font-medium rounded-lg hover:bg-muted/80 transition">Cancel</button>
                  <button onClick={handleCreateTask} className="flex-1 py-2.5 bg-primary text-primary-foreground text-sm font-medium rounded-lg hover:bg-primary/90 transition">Create Task</button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
