"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { FolderOpen, ChevronRight } from "lucide-react"

interface Project {
  id: string
  name: string
  description: string
  status: string
  start_date: string
  end_date: string
}

const statusColors: Record<string, string> = {
  active: "bg-emerald-500/10 text-emerald-400",
  on_hold: "bg-amber-500/10 text-amber-400",
  completed: "bg-blue-500/10 text-blue-400",
  cancelled: "bg-red-500/10 text-red-400",
}

export default function ClientProjects() {
  const router = useRouter()
  const [projects, setProjects] = useState<Project[]>([])

  useEffect(() => {
    fetch("/client-portal/api/projects", { credentials: "include" })
      .then((r) => r.json())
      .then((d) => setProjects(d.projects || []))
      .catch(() => {})
  }, [])

  return (
    <div>
      <h1 className="text-xl font-bold text-white mb-1">Projects</h1>
      <p className="text-sm text-[#6a6a75] mb-6">View your project milestones and progress</p>

      {projects.length === 0 ? (
        <div className="text-center py-16">
          <FolderOpen className="h-10 w-10 text-[#2a2a35] mx-auto mb-3" />
          <p className="text-sm text-[#6a6a75]">No projects yet</p>
        </div>
      ) : (
        <div className="space-y-3">
          {projects.map((p) => (
            <button
              key={p.id}
              onClick={() => router.push(`/client-portal/projects/${p.id}`)}
              className="w-full bg-[#0d1117] border border-[#1a1a24] rounded-xl p-5 text-left hover:border-[#1BB0CE]/30 transition-all group"
            >
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-1">
                    <h3 className="text-white font-semibold">{p.name}</h3>
                    <span className={`text-[10px] font-medium px-2 py-0.5 rounded-full ${statusColors[p.status] || "bg-zinc-500/10 text-zinc-400"}`}>
                      {p.status.replace("_", " ")}
                    </span>
                  </div>
                  {p.description && (
                    <p className="text-sm text-[#8a8a95] line-clamp-1">{p.description}</p>
                  )}
                  <div className="flex gap-4 mt-2 text-[11px] text-[#6a6a75]">
                    {p.start_date && <span>Start: {new Date(p.start_date).toLocaleDateString()}</span>}
                    {p.end_date && <span>Due: {new Date(p.end_date).toLocaleDateString()}</span>}
                  </div>
                </div>
                <ChevronRight className="h-5 w-5 text-[#2a2a35] group-hover:text-[#1BB0CE] transition-colors" />
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
