"use client"

import { useState, useEffect, useCallback } from "react"
import { useParams, useRouter } from "next/navigation"
import { PageHeader } from "@/components/shared/page-header"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { CustomFieldsSection } from "@/components/shared/custom-fields-section"
import {
  ArrowLeft, Calendar, User, Building2, DollarSign, Plus, CheckCircle2,
  Circle, Clock, AlertCircle, ChevronDown, ChevronRight, GripVertical,
} from "lucide-react"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

interface Milestone {
  id: string
  name: string
  description: string
  sort_order: number
  status: string
  start_date: string
  due_date: string
  completed_at: string
  created_at: string
  tasks: Task[]
}

interface Task {
  id: string
  title: string
  description: string
  status: string
  due_date: string
  completed_at: string
  assigned_to: string
  created_at: string
}

const milestoneStatusConfig: Record<string, { icon: any; class: string; label: string }> = {
  pending: { icon: Circle, class: "text-zinc-400", label: "Pending" },
  in_progress: { icon: Clock, class: "text-blue-500", label: "In Progress" },
  completed: { icon: CheckCircle2, class: "text-emerald-500", label: "Completed" },
  cancelled: { icon: AlertCircle, class: "text-red-500", label: "Cancelled" },
}

const taskStatusColors: Record<string, string> = {
  pending: "bg-zinc-500",
  in_progress: "bg-blue-500",
  completed: "bg-emerald-500",
  cancelled: "bg-red-500",
}

export default function ProjectDetailPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const [project, setProject] = useState<any>(null)
  const [milestones, setMilestones] = useState<Milestone[]>([])
  const [statuses, setStatuses] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [expandedMilestones, setExpandedMilestones] = useState<Set<string>>(new Set())
  const [newMilestoneName, setNewMilestoneName] = useState("")
  const [addingMilestone, setAddingMilestone] = useState(false)
  const [newTaskInputs, setNewTaskInputs] = useState<Record<string, string>>({})

  const fetchProject = useCallback(async () => {
    try {
      const [pRes, mRes, sRes] = await Promise.all([
        fetch(`/api/projects/${id}`),
        fetch(`/api/projects/${id}/milestones`),
        fetch("/api/project-statuses"),
      ])
      setProject(await pRes.json())
      setMilestones(await mRes.json())
      setStatuses(await sRes.json())
    } catch (e) {
      console.error("Failed to load project", e)
    } finally {
      setLoading(false)
    }
  }, [id])

  useEffect(() => { fetchProject() }, [fetchProject])

  const updateProjectStatus = async (statusId: string) => {
    await fetch(`/api/projects/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ statusId }),
    })
    fetchProject()
  }

  const updateMilestoneStatus = async (milestoneId: string, status: string) => {
    await fetch(`/api/milestones/${milestoneId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    })
    fetchProject()
  }

  const addMilestone = async () => {
    if (!newMilestoneName.trim()) return
    setAddingMilestone(true)
    try {
      await fetch(`/api/projects/${id}/milestones`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: newMilestoneName.trim() }),
      })
      setNewMilestoneName("")
      fetchProject()
    } finally {
      setAddingMilestone(false)
    }
  }

  const addTask = async (milestoneId: string) => {
    const title = newTaskInputs[milestoneId]?.trim()
    if (!title) return
    try {
      await fetch(`/api/tasks`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title,
          projectId: id,
          milestoneId,
        }),
      })
      setNewTaskInputs((prev) => ({ ...prev, [milestoneId]: "" }))
      fetchProject()
    } catch (e) {
      console.error("Failed to add task", e)
    }
  }

  const toggleMilestone = (msId: string) => {
    setExpandedMilestones((prev) => {
      const next = new Set(prev)
      if (next.has(msId)) next.delete(msId)
      else next.add(msId)
      return next
    })
  }

  const formatDate = (d: string) => d ? new Date(d).toLocaleDateString() : "—"
  const formatCurrency = (n: number) => n ? `R${Number(n).toLocaleString()}` : ""

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="h-10 w-48 animate-pulse rounded bg-muted" />
        <div className="grid gap-4 md:grid-cols-3">
          {[1, 2, 3].map((i) => <div key={i} className="h-24 animate-pulse rounded-lg bg-muted" />)}
        </div>
      </div>
    )
  }

  if (!project) return <div className="p-8 text-center text-muted-foreground">Project not found</div>

  const now = new Date()
  const start = project.start_date ? new Date(project.start_date) : now
  const end = project.target_end_date ? new Date(project.target_end_date) : new Date(start.getTime() + 60 * 86400000)
  const totalDays = Math.max(1, (end.getTime() - start.getTime()) / 86400000)

  const completedMilestones = milestones.filter((m) => m.status === "completed").length
  const progress = milestones.length ? Math.round((completedMilestones / milestones.length) * 100) : 0

  return (
    <div className="space-y-6">
      <PageHeader title={project.name} description={`Project · ${project.company_name}`}>
        <Button variant="outline" size="sm" onClick={() => router.push("/projects")}>
          <ArrowLeft className="mr-1.5 h-4 w-4" /> Back
        </Button>
      </PageHeader>

      {/* Overview Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card className="p-4 space-y-1">
          <p className="text-xs text-muted-foreground">Customer</p>
          <p className="flex items-center gap-1.5 text-sm font-medium"><Building2 className="h-4 w-4 text-muted-foreground" />{project.company_name}</p>
        </Card>
        <Card className="p-4 space-y-1">
          <p className="text-xs text-muted-foreground">Owner</p>
          <p className="flex items-center gap-1.5 text-sm font-medium"><User className="h-4 w-4 text-muted-foreground" />{project.owner_name}</p>
        </Card>
        <Card className="p-4 space-y-1">
          <p className="text-xs text-muted-foreground">Timeline</p>
          <p className="flex items-center gap-1.5 text-sm font-medium"><Calendar className="h-4 w-4 text-muted-foreground" />{formatDate(project.start_date)} — {formatDate(project.target_end_date)}</p>
        </Card>
        <Card className="p-4 space-y-1">
          <p className="text-xs text-muted-foreground">Budget</p>
          <p className="flex items-center gap-1.5 text-sm font-medium"><DollarSign className="h-4 w-4 text-muted-foreground" />{project.budget ? formatCurrency(project.budget) : "—"}</p>
        </Card>
      </div>

      {/* Status & Progress */}
      <Card className="p-4">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <p className="text-sm font-medium">Status</p>
            <Select value={project.status_id} onValueChange={updateProjectStatus}>
              <SelectTrigger className="h-8 w-[160px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {statuses.map((s) => (
                  <SelectItem key={s.id} value={s.id}>
                    <span className="flex items-center gap-2">
                      <span className="h-2 w-2 rounded-full" style={{ backgroundColor: s.color }} />
                      {s.name}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex items-center gap-3">
            <p className="text-sm text-muted-foreground">{progress}% complete</p>
            <div className="h-2 w-32 overflow-hidden rounded-full bg-muted">
              <div
                className="h-full rounded-full bg-primary transition-all"
                style={{ width: `${progress}%` }}
              />
            </div>
          </div>
        </div>
      </Card>

      {/* Gantt Chart */}
      <Card className="p-4">
        <p className="text-sm font-medium mb-3">Timeline</p>
        <div className="relative overflow-x-auto">
          <div className="min-w-[500px] space-y-2">
            {milestones.map((ms) => {
              const msStart = ms.start_date ? new Date(ms.start_date) : start
              const msEnd = ms.due_date ? new Date(ms.due_date) : end
              const left = Math.max(0, ((msStart.getTime() - start.getTime()) / 86400000) / totalDays * 100)
              const width = Math.max(3, ((msEnd.getTime() - msStart.getTime()) / 86400000) / totalDays * 100)
              const config = milestoneStatusConfig[ms.status] || milestoneStatusConfig.pending
              return (
                <div key={ms.id} className="flex items-center gap-3">
                  <span className="w-48 text-xs truncate shrink-0">{ms.name}</span>
                  <div className="relative flex-1 h-6">
                    <div className="absolute inset-0 rounded bg-muted/30" />
                    <div
                      className={`absolute top-1 h-4 rounded transition-all ${config.class.replace("text-", "bg-").replace("500", "500/80")}`}
                      style={{ left: `${left}%`, width: `${width}%`, backgroundColor: ms.status === "completed" ? "#22c55e" : ms.status === "in_progress" ? "#3b82f6" : ms.status === "cancelled" ? "#ef4444" : "#a1a1aa" }}
                    >
                      <span className="px-2 text-[10px] leading-4 text-white block truncate opacity-80">{ms.name}</span>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      </Card>

      {/* Custom Fields */}
      {project.custom_fields && Object.keys(project.custom_fields).length > 0 && (
        <CustomFieldsSection
          entityType="project"
          customFields={project.custom_fields}
          entityId={project.id}
          apiEndpoint={`/api/projects/${project.id}`}
          title="Custom Fields"
        />
      )}

      {/* Milestones */}
      <Card className="divide-y">
        <div className="flex items-center justify-between px-4 py-3">
          <p className="text-sm font-medium">Milestones ({milestones.length})</p>
          <div className="flex items-center gap-2">
            <Input
              placeholder="New milestone name..."
              value={newMilestoneName}
              onChange={(e) => setNewMilestoneName(e.target.value)}
              className="h-8 w-56 text-sm"
              onKeyDown={(e) => e.key === "Enter" && addMilestone()}
            />
            <Button size="sm" variant="outline" className="h-8" onClick={addMilestone} disabled={addingMilestone || !newMilestoneName.trim()}>
              <Plus className="h-3.5 w-3.5" /> Add
            </Button>
          </div>
        </div>

        {milestones.length === 0 && (
          <div className="p-8 text-center text-sm text-muted-foreground">No milestones yet</div>
        )}

        {milestones.map((ms) => {
          const config = milestoneStatusConfig[ms.status] || milestoneStatusConfig.pending
          const isExpanded = expandedMilestones.has(ms.id)

          return (
            <div key={ms.id}>
              <div
                className="flex items-center gap-3 px-4 py-3 hover:bg-muted/50 cursor-pointer transition-colors"
                onClick={() => toggleMilestone(ms.id)}
              >
                <div className="flex items-center gap-2 flex-1 min-w-0">
                  {isExpanded ? <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" /> : <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" />}
                  <config.icon className={`h-4 w-4 ${config.class}`} />
                  <span className="text-sm font-medium truncate">{ms.name}</span>
                  <Badge variant="outline" className="text-[10px] h-5">{config.label}</Badge>
                </div>
                <div className="flex items-center gap-1 text-xs text-muted-foreground shrink-0">
                  {ms.start_date && <span>{formatDate(ms.start_date)}</span>}
                  {ms.start_date && ms.due_date && <span>→</span>}
                  {ms.due_date && <span>{formatDate(ms.due_date)}</span>}
                </div>
                <Select
                  value={ms.status}
                  onValueChange={(v) => updateMilestoneStatus(ms.id, v)}
                >
                  <SelectTrigger className="h-7 w-[110px] text-xs" onPointerDown={(e) => e.stopPropagation()}>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="pending">Pending</SelectItem>
                    <SelectItem value="in_progress">In Progress</SelectItem>
                    <SelectItem value="completed">Completed</SelectItem>
                    <SelectItem value="cancelled">Cancelled</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {isExpanded && (
                <div className="border-t bg-muted/20 px-4 py-3 space-y-2">
                  {ms.description && (
                    <p className="text-xs text-muted-foreground">{ms.description}</p>
                  )}
                  {ms.tasks.length === 0 && (
                    <p className="text-xs text-muted-foreground">No tasks yet</p>
                  )}
                  {ms.tasks.map((task) => (
                    <div key={task.id} className="flex items-center gap-2 pl-2">
                      <span className={`h-2 w-2 rounded-full shrink-0 ${taskStatusColors[task.status] || "bg-zinc-400"}`} />
                      <span className="text-xs flex-1">{task.title}</span>
                      <span className="text-[10px] text-muted-foreground capitalize">{task.status.replace("_", " ")}</span>
                    </div>
                  ))}
                  <div className="flex items-center gap-2 pt-1">
                    <Input
                      placeholder="Add task..."
                      value={newTaskInputs[ms.id] || ""}
                      onChange={(e) => setNewTaskInputs((prev) => ({ ...prev, [ms.id]: e.target.value }))}
                      className="h-7 text-xs flex-1"
                      onKeyDown={(e) => e.key === "Enter" && addTask(ms.id)}
                    />
                    <Button
                      size="sm"
                      variant="ghost"
                      className="h-7 text-xs"
                      onClick={() => addTask(ms.id)}
                      disabled={!newTaskInputs[ms.id]?.trim()}
                    >
                      <Plus className="h-3 w-3 mr-1" /> Task
                    </Button>
                  </div>
                </div>
              )}
            </div>
          )
        })}
      </Card>
    </div>
  )
}
