"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { FolderKanban, Plus, ArrowLeft, LayoutGrid, Trash2, Edit3, Check, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { useTaskStore, Project } from "@/stores/useTaskStore"
import { toast } from "sonner"

interface ProjectWithStats extends Project {
  taskCount: number
  completedTasks: number
  inProgressTasks: number
}

const PRESET_COLORS = [
  "#3b82f6", // blue
  "#ef4444", // red
  "#22c55e", // green
  "#f59e0b", // amber
  "#8b5cf6", // violet
  "#ec4899", // pink
  "#06b6d4", // cyan
  "#f97316", // orange
  "#84cc16", // lime
  "#6366f1", // indigo
]

export default function ProjectsPage() {
  const router = useRouter()
  const { projects, tasks, addProject, updateProject, deleteProject, syncFromServer } = useTaskStore()
  
  
  const [authReady, setAuthReady] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [projectsWithStats, setProjectsWithStats] = useState<ProjectWithStats[]>([])
  
  // Create project dialog state
  const [createDialogOpen, setCreateDialogOpen] = useState(false)
  const [newProjectName, setNewProjectName] = useState("")
  const [newProjectDescription, setNewProjectDescription] = useState("")
  const [newProjectColor, setNewProjectColor] = useState(PRESET_COLORS[0])
  const [isCreating, setIsCreating] = useState(false)
  
  // Edit state
  const [editingProjectId, setEditingProjectId] = useState<string | null>(null)
  const [editName, setEditName] = useState("")
  const [editDescription, setEditDescription] = useState("")
  const [editColor, setEditColor] = useState("")
  
  // Delete confirmation
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null)

  // 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 data when auth is ready
  useEffect(() => {
    if (!authReady) return
    syncFromServer().then(() => setIsLoading(false))
  }, [authReady, syncFromServer])

  // Calculate project stats
  useEffect(() => {
    const stats = projects.map(project => {
      const projectTasks = tasks.filter(t => t.projectId === project.id)
      return {
        ...project,
        taskCount: projectTasks.length,
        completedTasks: projectTasks.filter(t => t.status === "done" || t.status === "archived").length,
        inProgressTasks: projectTasks.filter(t => t.status === "in-progress" || t.status === "review").length,
      }
    })
    setProjectsWithStats(stats)
  }, [projects, tasks])

  const handleCreateProject = async () => {
    if (!newProjectName.trim()) {
      toast.error("Project name is required")
      return
    }

    setIsCreating(true)
    try {
      // addProject only accepts name and description, color is assigned randomly
      // We'll update the color immediately after creation
      await addProject(
        newProjectName.trim(),
        newProjectDescription.trim() || undefined
      )
      
      // The project was created, now we need to sync and update the color
      await syncFromServer()
      
      // Find the newly created project (most recent one with matching name)
      const newProject = projects
        .filter(p => p.name === newProjectName.trim())
        .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0]
      
      if (newProject && newProject.color !== newProjectColor) {
        await updateProject(newProject.id, { color: newProjectColor })
      }
      
      toast.success("Project created successfully")
      setCreateDialogOpen(false)
      setNewProjectName("")
      setNewProjectDescription("")
      setNewProjectColor(PRESET_COLORS[0])
    } catch (error) {
      toast.error("Failed to create project")
      console.error(error)
    } finally {
      setIsCreating(false)
    }
  }

  const startEdit = (project: Project) => {
    setEditingProjectId(project.id)
    setEditName(project.name)
    setEditDescription(project.description || "")
    setEditColor(project.color)
  }

  const cancelEdit = () => {
    setEditingProjectId(null)
    setEditName("")
    setEditDescription("")
    setEditColor("")
  }

  const saveEdit = async (projectId: string) => {
    if (!editName.trim()) {
      toast.error("Project name is required")
      return
    }

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

  const handleDeleteProject = async (projectId: string) => {
    try {
      await deleteProject(projectId)
      toast.success("Project deleted successfully")
      setDeleteConfirmId(null)
    } catch (error) {
      toast.error("Failed to delete project")
      console.error(error)
    }
  }

  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>
    )
  }

  return (
    <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("/")}
              >
                <ArrowLeft className="w-4 h-4 mr-2" />
                Back to Board
              </Button>
              <div>
                <h1 className="text-xl md:text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                  Projects
                </h1>
                <p className="text-xs md:text-sm text-slate-400 mt-1">
                  Manage your projects and view task statistics
                </p>
              </div>
            </div>
            <Button onClick={() => setCreateDialogOpen(true)}>
              <Plus className="w-4 h-4 mr-2" />
              New Project
            </Button>
          </div>
        </div>
      </header>

      <div className="max-w-[1800px] mx-auto px-4 py-6">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <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 projects...</span>
            </div>
          </div>
        ) : projectsWithStats.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-slate-400">
            <FolderKanban className="w-16 h-16 mb-4 text-slate-600" />
            <h3 className="text-lg font-medium text-slate-300 mb-2">No Projects Yet</h3>
            <p className="text-sm mb-6 text-center max-w-md">
              Create your first project to start organizing your tasks and sprints.
            </p>
            <Button onClick={() => setCreateDialogOpen(true)}>
              <Plus className="w-4 h-4 mr-2" />
              Create First Project
            </Button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {projectsWithStats.map((project) => (
              <Card
                key={project.id}
                className="bg-slate-900 border-slate-800 hover:border-slate-600 transition-all group overflow-hidden"
              >
                {/* Color bar */}
                <div 
                  className="h-2 w-full"
                  style={{ backgroundColor: project.color }}
                />
                
                <CardHeader className="pb-3">
                  {editingProjectId === project.id ? (
                    <div className="space-y-3">
                      <Input
                        value={editName}
                        onChange={(e) => setEditName(e.target.value)}
                        className="bg-slate-800 border-slate-700 text-white"
                        placeholder="Project name"
                        autoFocus
                      />
                      <Textarea
                        value={editDescription}
                        onChange={(e) => setEditDescription(e.target.value)}
                        className="bg-slate-800 border-slate-700 text-white text-sm"
                        placeholder="Description (optional)"
                        rows={2}
                      />
                      <div className="flex flex-wrap 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 scale-110" : "border-transparent"
                            }`}
                            style={{ backgroundColor: color }}
                          />
                        ))}
                      </div>
                      <div className="flex gap-2">
                        <Button size="sm" onClick={() => saveEdit(project.id)}>
                          <Check className="w-3 h-3 mr-1" />
                          Save
                        </Button>
                        <Button size="sm" variant="outline" onClick={cancelEdit}>
                          <X className="w-3 h-3 mr-1" />
                          Cancel
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-start justify-between">
                      <div 
                        className="flex-1 min-w-0 cursor-pointer"
                        onClick={() => router.push(`/projects/${project.id}`)}
                      >
                        <h3 className="font-semibold text-white truncate group-hover:text-blue-400 transition-colors">
                          {project.name}
                        </h3>
                        {project.description && (
                          <p className="text-sm text-slate-400 mt-1 line-clamp-2">
                            {project.description}
                          </p>
                        )}
                      </div>
                      <div className="flex items-center gap-1 ml-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button
                          onClick={() => startEdit(project)}
                          className="p-1.5 rounded hover:bg-slate-800 text-slate-400 hover:text-blue-400"
                          title="Edit project"
                        >
                          <Edit3 className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => setDeleteConfirmId(project.id)}
                          className="p-1.5 rounded hover:bg-slate-800 text-slate-400 hover:text-red-400"
                          title="Delete project"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  )}
                </CardHeader>
                
                <CardContent 
                  className="pt-0 cursor-pointer"
                  onClick={() => router.push(`/projects/${project.id}`)}
                >
                  {/* Stats */}
                  <div className="grid grid-cols-3 gap-2 mb-4">
                    <div className="bg-slate-800/50 rounded-lg p-2 text-center">
                      <p className="text-xl font-bold text-white">{project.taskCount}</p>
                      <p className="text-xs text-slate-400">Total</p>
                    </div>
                    <div className="bg-slate-800/50 rounded-lg p-2 text-center">
                      <p className="text-xl font-bold text-emerald-400">{project.completedTasks}</p>
                      <p className="text-xs text-slate-400">Done</p>
                    </div>
                    <div className="bg-slate-800/50 rounded-lg p-2 text-center">
                      <p className="text-xl font-bold text-blue-400">{project.inProgressTasks}</p>
                      <p className="text-xs text-slate-400">Active</p>
                    </div>
                  </div>

                  {/* Progress bar */}
                  {project.taskCount > 0 && (
                    <div className="space-y-1">
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-slate-400">Progress</span>
                        <span className="text-slate-300">
                          {Math.round((project.completedTasks / project.taskCount) * 100)}%
                        </span>
                      </div>
                      <div className="h-2 bg-slate-800 rounded-full overflow-hidden">
                        <div
                          className="h-full rounded-full transition-all bg-emerald-500"
                          style={{ 
                            width: `${(project.completedTasks / project.taskCount) * 100}%`,
                            backgroundColor: project.color 
                          }}
                        />
                      </div>
                    </div>
                  )}

                  {/* View link */}
                  <div className="flex items-center justify-center gap-1 text-xs text-slate-500 group-hover:text-blue-400 transition-colors mt-4 pt-3 border-t border-slate-800">
                    <LayoutGrid className="w-3 h-3" />
                    <span>View Details</span>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Create Project Dialog */}
      <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
        <DialogContent className="bg-slate-900 border-slate-800 text-white w-[95vw] max-w-lg">
          <DialogHeader>
            <DialogTitle>Create New Project</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div>
              <label className="text-sm text-slate-400">Project Name *</label>
              <Input
                value={newProjectName}
                onChange={(e) => setNewProjectName(e.target.value)}
                placeholder="e.g., Website Redesign"
                className="mt-1 bg-slate-800 border-slate-700 text-white"
                onKeyDown={(e) => {
                  if (e.key === "Enter" && !e.shiftKey) {
                    e.preventDefault()
                    handleCreateProject()
                  }
                }}
              />
            </div>
            <div>
              <label className="text-sm text-slate-400">Description</label>
              <Textarea
                value={newProjectDescription}
                onChange={(e) => setNewProjectDescription(e.target.value)}
                placeholder="What is this project about?"
                rows={3}
                className="mt-1 bg-slate-800 border-slate-700 text-white"
              />
            </div>
            <div>
              <label className="text-sm text-slate-400 mb-2 block">Color</label>
              <div className="flex flex-wrap gap-2">
                {PRESET_COLORS.map((color) => (
                  <button
                    key={color}
                    type="button"
                    onClick={() => setNewProjectColor(color)}
                    className={`w-8 h-8 rounded-full border-2 transition-all ${
                      newProjectColor === color 
                        ? "border-white scale-110 ring-2 ring-white/20" 
                        : "border-transparent hover:scale-105"
                    }`}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>
          </div>
          <div className="flex gap-2 justify-end">
            <Button variant="outline" onClick={() => setCreateDialogOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleCreateProject} disabled={isCreating || !newProjectName.trim()}>
              {isCreating ? "Creating..." : "Create Project"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={!!deleteConfirmId} onOpenChange={() => setDeleteConfirmId(null)}>
        <DialogContent className="bg-slate-900 border-slate-800 text-white w-[95vw] max-w-md">
          <DialogHeader>
            <DialogTitle>Delete Project?</DialogTitle>
          </DialogHeader>
          <div className="py-4">
            <p className="text-slate-300">
              Are you sure you want to delete this project? This action cannot be undone.
            </p>
            <p className="text-slate-400 text-sm mt-2">
              Tasks in this project will remain but will no longer be associated with a project.
            </p>
          </div>
          <div className="flex gap-2 justify-end">
            <Button variant="outline" onClick={() => setDeleteConfirmId(null)}>
              Cancel
            </Button>
            <Button 
              variant="destructive" 
              onClick={() => deleteConfirmId && handleDeleteProject(deleteConfirmId)}
            >
              Delete
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
