"use client"

import { useEffect, useState, useMemo } from "react"
import { useRouter, useParams } from "next/navigation"
import {
  DndContext,
  DragEndEvent,
  DragOverlay,
  DragStartEvent,
  PointerSensor,
  useSensor,
  useSensors,
  closestCorners,
} from "@dnd-kit/core"
import {
  SortableContext,
  verticalListSortingStrategy,
  useSortable,
} from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { 
  ArrowLeft, 
  FolderKanban, 
  Plus, 
  Edit3, 
  Check, 
  X, 
  GripVertical,
  LayoutGrid,
  ListTodo,
  Trash2,
  MessageSquare,
  Inbox
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { useTaskStore, Task, Project } from "@/stores/useTaskStore"
import { toast } from "sonner"

const PRESET_COLORS = [
  "#3b82f6", "#ef4444", "#22c55e", "#f59e0b", "#8b5cf6",
  "#ec4899", "#06b6d4", "#f97316", "#84cc16", "#6366f1",
]

const priorityColors: Record<string, string> = {
  low: "bg-slate-600",
  medium: "bg-blue-600",
  high: "bg-orange-600",
  urgent: "bg-red-600",
}

const statusLabels: Record<string, string> = {
  open: "Open",
  todo: "To Do",
  blocked: "Blocked",
  "in-progress": "In Progress",
  review: "Review",
  validate: "Validate",
  archived: "Archived",
  canceled: "Canceled",
  done: "Done",
}

// Sortable Task Card Component
function SortableTaskCard({
  task,
  onClick,
}: {
  task: Task
  onClick: () => void
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: task.id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  }

  return (
    <Card
      ref={setNodeRef}
      style={style}
      className="bg-slate-800 border-slate-700 cursor-pointer hover:border-slate-600 transition-colors group"
      onClick={onClick}
    >
      <CardContent className="p-3">
        <div className="flex items-start gap-2">
          <div
            {...attributes}
            {...listeners}
            className="mt-0.5 opacity-0 group-hover:opacity-100 transition-opacity cursor-grab active:cursor-grabbing"
          >
            <GripVertical className="w-4 h-4 text-slate-500" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-start justify-between gap-2">
              <h4 className="text-sm font-medium text-slate-200 line-clamp-2">
                {task.title}
              </h4>
            </div>
            <div className="flex items-center gap-2 mt-2 flex-wrap">
              <Badge
                className={`${priorityColors[task.priority]} text-white text-xs`}
              >
                {task.priority}
              </Badge>
              <Badge variant="outline" className="text-xs border-slate-600 text-slate-400">
                {task.type}
              </Badge>
              <Badge variant="secondary" className="text-xs bg-slate-700 text-slate-300">
                {statusLabels[task.status]}
              </Badge>
              {task.comments && task.comments.length > 0 && (
                <span className="text-xs text-slate-500 flex items-center gap-1">
                  <MessageSquare className="w-3 h-3" />
                  {task.comments.length}
                </span>
              )}
            </div>
            {task.assigneeName && (
              <p className="text-xs text-slate-500 mt-2">
                Assigned to: {task.assigneeName}
              </p>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

// Drag Overlay Task Card
function DragOverlayTaskCard({ task }: { task: Task }) {
  return (
    <Card className="bg-slate-800 border-slate-600 shadow-xl rotate-2">
      <CardContent className="p-3">
        <div className="flex items-start gap-2">
          <GripVertical className="w-4 h-4 text-slate-500 mt-0.5" />
          <div className="flex-1 min-w-0">
            <h4 className="text-sm font-medium text-slate-200 line-clamp-2">
              {task.title}
            </h4>
            <div className="flex items-center gap-2 mt-2">
              <Badge className={`${priorityColors[task.priority]} text-white text-xs`}>
                {task.priority}
              </Badge>
              <Badge variant="outline" className="text-xs border-slate-600 text-slate-400">
                {task.type}
              </Badge>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

// Unassigned Tasks Panel Component
function UnassignedPanel({
  tasks,
  onTaskClick,
}: {
  tasks: Task[]
  onTaskClick: (taskId: string) => void
}) {
  const { setNodeRef, isOver } = useSortable({
    id: "unassigned-drop-zone",
    data: { type: "unassigned" },
  })

  return (
    <div
      ref={setNodeRef}
      className={`bg-slate-900/50 rounded-lg p-4 border-2 border-dashed transition-colors ${
        isOver ? "border-blue-500 bg-blue-500/10" : "border-slate-700"
      }`}
    >
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <Inbox className="w-4 h-4 text-slate-400" />
          <h3 className="font-medium text-slate-300">Unassigned Tasks</h3>
        </div>
        <Badge variant="secondary" className="text-xs bg-slate-800 text-slate-400">
          {tasks.length}
        </Badge>
      </div>
      
      <SortableContext items={tasks.map((t) => t.id)} strategy={verticalListSortingStrategy}>
        <div className="space-y-2 min-h-[100px]">
          {tasks.length === 0 ? (
            <div className="text-center py-8 text-slate-500 text-sm">
              <p>Drop tasks here to unassign</p>
              <p className="text-xs mt-1">from this project</p>
            </div>
          ) : (
            tasks.map((task) => (
              <SortableTaskCard
                key={task.id}
                task={task}
                onClick={() => onTaskClick(task.id)}
              />
            ))
          )}
        </div>
      </SortableContext>
    </div>
  )
}

export default function ProjectDetailPage() {
  const params = useParams<{ id: string }>()
  const router = useRouter()
  const projectId = params.id

  const {
    projects,
    tasks,
    currentUser,
    updateTask,
    updateProject,
    deleteProject,
    syncFromServer,
    addTask,
  } = useTaskStore()

  const [authReady, setAuthReady] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [project, setProject] = useState<Project | null>(null)
  
  // Edit state
  const [isEditing, setIsEditing] = useState(false)
  const [editName, setEditName] = useState("")
  const [editDescription, setEditDescription] = useState("")
  const [editColor, setEditColor] = useState("")
  
  // Drag and drop
  const [activeId, setActiveId] = useState<string | null>(null)
  
  // New task dialog
  const [newTaskOpen, setNewTaskOpen] = useState(false)
  const [newTask, setNewTask] = useState<Partial<Task>>({
    title: "",
    description: "",
    type: "task",
    priority: "medium",
    status: "open",
  })

  // Sensors for drag detection
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: { distance: 8 },
    })
  )

  // Check auth
  useEffect(() => {
    let isMounted = true
    const loadSession = async () => {
      try {
        const res = await fetch("/api/auth/session", { cache: "no-store" })
        if (!res.ok) {
          if (isMounted) router.replace("/login")
          return
        }
        if (isMounted) setAuthReady(true)
      } catch {
        if (isMounted) router.replace("/login")
      }
    }
    loadSession()
    return () => { isMounted = false }
  }, [router])

  // Sync and find project
  useEffect(() => {
    if (!authReady) return
    
    const load = async () => {
      await syncFromServer()
      const found = projects.find((p) => p.id === projectId)
      if (found) {
        setProject(found)
        setEditName(found.name)
        setEditDescription(found.description || "")
        setEditColor(found.color)
      }
      setIsLoading(false)
    }
    load()
  }, [authReady, projectId, projects, syncFromServer])

  // Get project tasks
  const projectTasks = useMemo(() => {
    return tasks
      .filter((t) => t.projectId === projectId)
      .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
  }, [tasks, projectId])

  // Get unassigned tasks (for this user's view - tasks without project)
  const unassignedTasks = useMemo(() => {
    return tasks
      .filter((t) => !t.projectId && t.createdById === currentUser.id)
      .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
  }, [tasks, currentUser.id])

  // Stats
  const stats = useMemo(() => {
    const total = projectTasks.length
    const completed = projectTasks.filter((t) => t.status === "done" || t.status === "archived").length
    const inProgress = projectTasks.filter((t) => t.status === "in-progress" || t.status === "review").length
    const todo = projectTasks.filter((t) => t.status === "open" || t.status === "todo").length
    return { total, completed, inProgress, todo }
  }, [projectTasks])

  const handleSaveEdit = async () => {
    if (!project || !editName.trim()) {
      toast.error("Project name is required")
      return
    }

    try {
      await updateProject(project.id, {
        name: editName.trim(),
        description: editDescription.trim() || undefined,
        color: editColor,
      })
      toast.success("Project updated successfully")
      setIsEditing(false)
    } catch (error) {
      toast.error("Failed to update project")
      console.error(error)
    }
  }

  const handleDeleteProject = async () => {
    if (!project) return
    if (!window.confirm("Are you sure you want to delete this project? This cannot be undone.")) return

    try {
      await deleteProject(project.id)
      toast.success("Project deleted successfully")
      router.push("/projects")
    } catch (error) {
      toast.error("Failed to delete project")
      console.error(error)
    }
  }

  const handleDragStart = (event: DragStartEvent) => {
    setActiveId(event.active.id as string)
  }

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event
    setActiveId(null)

    if (!over) return

    const taskId = active.id as string
    const overId = over.id as string

    // If dropped on unassigned zone, remove project association
    if (overId === "unassigned-drop-zone") {
      const task = tasks.find((t) => t.id === taskId)
      if (task && task.projectId === projectId) {
        updateTask(taskId, { projectId: undefined, sprintId: undefined })
        toast.success("Task unassigned from project")
      }
      return
    }

    // If dropped on project zone, assign to this project
    if (overId === "project-drop-zone") {
      const task = tasks.find((t) => t.id === taskId)
      if (task && task.projectId !== projectId) {
        updateTask(taskId, { projectId })
        toast.success("Task assigned to project")
      }
      return
    }

    // If dropped on another task, we could reorder (future enhancement)
    const overTask = tasks.find((t) => t.id === overId)
    if (overTask) {
      // Check if we need to move between projects
      const activeTask = tasks.find((t) => t.id === taskId)
      if (activeTask && overTask.projectId !== activeTask.projectId) {
        if (overTask.projectId === projectId) {
          updateTask(taskId, { projectId })
          toast.success("Task assigned to project")
        } else if (!overTask.projectId) {
          updateTask(taskId, { projectId: undefined, sprintId: undefined })
          toast.success("Task unassigned from project")
        }
      }
    }
  }

  const handleAddTask = async () => {
    if (!newTask.title?.trim() || !project) return

    try {
      await addTask({
        title: newTask.title.trim(),
        description: newTask.description?.trim() || undefined,
        type: (newTask.type || "task") as Task["type"],
        priority: (newTask.priority || "medium") as Task["priority"],
        status: (newTask.status || "open") as Task["status"],
        projectId: project.id,
        tags: [],
      })
      toast.success("Task created successfully")
      setNewTaskOpen(false)
      setNewTask({
        title: "",
        description: "",
        type: "task",
        priority: "medium",
        status: "open",
      })
    } catch (error) {
      toast.error("Failed to create task")
      console.error(error)
    }
  }

  const activeTask = activeId ? tasks.find((t) => t.id === activeId) : null

  if (!authReady) {
    return (
      <div className="min-h-screen bg-slate-950 text-slate-100 flex items-center justify-center">
        <p className="text-sm text-slate-400">Checking session...</p>
      </div>
    )
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-slate-950 text-slate-100 flex items-center justify-center">
        <div className="flex items-center gap-2 text-slate-400">
          <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span>Loading project...</span>
        </div>
      </div>
    )
  }

  if (!project) {
    return (
      <div className="min-h-screen bg-slate-950 text-slate-100 flex items-center justify-center">
        <div className="text-center">
          <FolderKanban className="w-16 h-16 mx-auto mb-4 text-slate-600" />
          <h2 className="text-xl font-semibold text-white mb-2">Project Not Found</h2>
          <p className="text-slate-400 mb-4">The project you&apos;re looking for doesn&apos;t exist.</p>
          <Button onClick={() => router.push("/projects")}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            Back to Projects
          </Button>
        </div>
      </div>
    )
  }

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCorners}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      <div className="min-h-screen bg-slate-950 text-slate-100">
        {/* Header */}
        <header className="border-b border-slate-800 bg-slate-900/50 backdrop-blur">
          <div className="max-w-[1800px] mx-auto px-4 py-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <Button
                  variant="outline"
                  className="border-slate-700 text-slate-200 hover:bg-slate-800"
                  onClick={() => router.push("/projects")}
                >
                  <ArrowLeft className="w-4 h-4 mr-2" />
                  Back
                </Button>
                
                {isEditing ? (
                  <div className="flex items-center gap-3">
                    <Input
                      value={editName}
                      onChange={(e) => setEditName(e.target.value)}
                      className="bg-slate-800 border-slate-700 text-white w-64"
                      placeholder="Project name"
                      autoFocus
                    />
                    <div className="flex gap-1">
                      {PRESET_COLORS.map((color) => (
                        <button
                          key={color}
                          type="button"
                          onClick={() => setEditColor(color)}
                          className={`w-6 h-6 rounded-full border-2 transition-all ${
                            editColor === color ? "border-white" : "border-transparent"
                          }`}
                          style={{ backgroundColor: color }}
                        />
                      ))}
                    </div>
                    <Button size="sm" onClick={handleSaveEdit}>
                      <Check className="w-4 h-4 mr-1" />
                      Save
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => setIsEditing(false)}>
                      <X className="w-4 h-4 mr-1" />
                      Cancel
                    </Button>
                  </div>
                ) : (
                  <div className="flex items-center gap-3">
                    <div 
                      className="w-4 h-4 rounded-full"
                      style={{ backgroundColor: project.color }}
                    />
                    <div>
                      <h1 className="text-xl md:text-2xl font-bold text-white">
                        {project.name}
                      </h1>
                      {project.description && (
                        <p className="text-sm text-slate-400">{project.description}</p>
                      )}
                    </div>
                    <button
                      onClick={() => setIsEditing(true)}
                      className="p-2 rounded hover:bg-slate-800 text-slate-400 hover:text-blue-400 opacity-0 group-hover:opacity-100 transition-opacity"
                      title="Edit project"
                    >
                      <Edit3 className="w-4 h-4" />
                    </button>
                  </div>
                )}
              </div>
              
              <div className="flex items-center gap-2">
                <Button variant="outline" onClick={handleDeleteProject} className="text-red-400 hover:text-red-300">
                  <Trash2 className="w-4 h-4 mr-2" />
                  Delete
                </Button>
                <Button onClick={() => setNewTaskOpen(true)}>
                  <Plus className="w-4 h-4 mr-2" />
                  Add Task
                </Button>
              </div>
            </div>
          </div>
        </header>

        <div className="max-w-[1800px] mx-auto px-4 py-6">
          {/* Stats */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <div className="bg-slate-900 border border-slate-800 rounded-lg p-4">
              <p className="text-3xl font-bold text-white">{stats.total}</p>
              <p className="text-sm text-slate-400">Total Tasks</p>
            </div>
            <div className="bg-slate-900 border border-slate-800 rounded-lg p-4">
              <p className="text-3xl font-bold text-emerald-400">{stats.completed}</p>
              <p className="text-sm text-slate-400">Completed</p>
            </div>
            <div className="bg-slate-900 border border-slate-800 rounded-lg p-4">
              <p className="text-3xl font-bold text-blue-400">{stats.inProgress}</p>
              <p className="text-sm text-slate-400">In Progress</p>
            </div>
            <div className="bg-slate-900 border border-slate-800 rounded-lg p-4">
              <p className="text-3xl font-bold text-slate-400">{stats.todo}</p>
              <p className="text-sm text-slate-400">To Do</p>
            </div>
          </div>

          {/* Progress bar */}
          {stats.total > 0 && (
            <div className="mb-6 bg-slate-900 border border-slate-800 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-slate-400">Project Progress</span>
                <span className="text-sm text-white font-medium">
                  {Math.round((stats.completed / stats.total) * 100)}% Complete
                </span>
              </div>
              <div className="h-3 bg-slate-800 rounded-full overflow-hidden">
                <div
                  className="h-full rounded-full transition-all"
                  style={{ 
                    width: `${(stats.completed / stats.total) * 100}%`,
                    backgroundColor: project.color 
                  }}
                />
              </div>
            </div>
          )}

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Project Tasks */}
            <div className="lg:col-span-2">
              <div 
                className="bg-slate-900/50 rounded-lg p-4 border border-slate-800"
                id="project-drop-zone"
              >
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-2">
                    <LayoutGrid className="w-4 h-4 text-slate-400" />
                    <h3 className="font-medium text-slate-300">Project Tasks</h3>
                  </div>
                  <Badge variant="secondary" className="text-xs bg-slate-800 text-slate-400">
                    {projectTasks.length}
                  </Badge>
                </div>

                <SortableContext items={projectTasks.map((t) => t.id)} strategy={verticalListSortingStrategy}>
                  <div className="space-y-2 min-h-[200px]">
                    {projectTasks.length === 0 ? (
                      <div className="text-center py-12 text-slate-500 border-2 border-dashed border-slate-800 rounded-lg">
                        <ListTodo className="w-12 h-12 mx-auto mb-3 text-slate-600" />
                        <p>No tasks in this project yet</p>
                        <p className="text-sm mt-1">Drag tasks here or click &quot;Add Task&quot;</p>
                      </div>
                    ) : (
                      projectTasks.map((task) => (
                        <SortableTaskCard
                          key={task.id}
                          task={task}
                          onClick={() => router.push(`/tasks/${task.id}`)}
                        />
                      ))
                    )}
                  </div>
                </SortableContext>
              </div>
            </div>

            {/* Unassigned Tasks Panel */}
            <div className="lg:col-span-1">
              <UnassignedPanel
                tasks={unassignedTasks}
                onTaskClick={(taskId) => router.push(`/tasks/${taskId}`)}
              />
            </div>
          </div>
        </div>

        {/* New Task Dialog */}
        <Dialog open={newTaskOpen} onOpenChange={setNewTaskOpen}>
          <DialogContent className="bg-slate-900 border-slate-800 text-white w-[95vw] max-w-lg">
            <DialogHeader>
              <DialogTitle>Create New Task</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div>
                <label className="text-sm text-slate-400">Title *</label>
                <Input
                  value={newTask.title}
                  onChange={(e) => setNewTask({ ...newTask, title: e.target.value })}
                  placeholder="Task title"
                  className="mt-1 bg-slate-800 border-slate-700 text-white"
                />
              </div>
              <div>
                <label className="text-sm text-slate-400">Description</label>
                <Textarea
                  value={newTask.description}
                  onChange={(e) => setNewTask({ ...newTask, description: e.target.value })}
                  placeholder="Task description"
                  rows={3}
                  className="mt-1 bg-slate-800 border-slate-700 text-white"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-slate-400">Type</label>
                  <select
                    value={newTask.type}
                    onChange={(e) => setNewTask({ ...newTask, type: e.target.value as Task["type"] })}
                    className="w-full mt-1 bg-slate-800 border border-slate-700 rounded px-3 py-2 text-white"
                  >
                    <option value="task">📋 Task</option>
                    <option value="idea">💡 Idea</option>
                    <option value="bug">🐛 Bug</option>
                    <option value="research">🔬 Research</option>
                    <option value="plan">📐 Plan</option>
                  </select>
                </div>
                <div>
                  <label className="text-sm text-slate-400">Priority</label>
                  <select
                    value={newTask.priority}
                    onChange={(e) => setNewTask({ ...newTask, priority: e.target.value as Task["priority"] })}
                    className="w-full mt-1 bg-slate-800 border border-slate-700 rounded px-3 py-2 text-white"
                  >
                    <option value="low">Low</option>
                    <option value="medium">Medium</option>
                    <option value="high">High</option>
                    <option value="urgent">Urgent</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="flex gap-2 justify-end">
              <Button variant="outline" onClick={() => setNewTaskOpen(false)}>
                Cancel
              </Button>
              <Button onClick={handleAddTask} disabled={!newTask.title?.trim()}>
                Create Task
              </Button>
            </div>
          </DialogContent>
        </Dialog>

        <DragOverlay>
          {activeTask ? <DragOverlayTaskCard task={activeTask} /> : null}
        </DragOverlay>
      </div>
    </DndContext>
  )
}
