"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Activity, GitMerge, FileText, LifeBuoy, ChevronRight } from "lucide-react"

interface Event {
  id: string
  event_type: "milestone" | "invoice" | "ticket"
  date: string
  name?: string
  status?: string
  progress?: number
  project_name?: string
  invoice_number?: string
  total_amount?: number
  currency?: string
  status_name?: string
  title?: string
}

export default function ClientActivity() {
  const router = useRouter()
  const [events, setEvents] = useState<Event[]>([])

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

  const getIcon = (type: string) => {
    if (type === "milestone") return <GitMerge className="h-4 w-4 text-[#1BB0CE]" />
    if (type === "invoice") return <FileText className="h-4 w-4 text-[#a855f7]" />
    return <LifeBuoy className="h-4 w-4 text-[#f59e0b]" />
  }

  const getStatusColor = (type: string, status: string) => {
    if (status === "approved" || status === "Paid" || status === "resolved" || status === "closed") return "text-emerald-400"
    if (status === "rejected" || status === "Overdue") return "text-red-400"
    return "text-amber-400"
  }

  const handleClick = (e: Event) => {
    if (e.event_type === "milestone") router.push(`/client-portal/projects/${e.id.split("-")[0] || ""}`)
    else if (e.event_type === "invoice") router.push(`/client-portal/invoices/${e.id}`)
    else if (e.event_type === "ticket") router.push(`/client-portal/support`)
  }

  const formatDate = (d: string) => {
    const date = new Date(d)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    if (diff < 86400000) return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
    if (diff < 604800000) return date.toLocaleDateString([], { weekday: "short" })
    return date.toLocaleDateString([], { month: "short", day: "numeric" })
  }

  return (
    <div>
      <h1 className="text-xl font-bold text-white mb-1">Activity</h1>
      <p className="text-sm text-[#6a6a75] mb-6">Recent project updates and changes</p>

      {events.length === 0 ? (
        <div className="text-center py-16">
          <Activity className="h-10 w-10 text-[#2a2a35] mx-auto mb-3" />
          <p className="text-sm text-[#6a6a75]">No recent activity</p>
        </div>
      ) : (
        <div className="relative">
          <div className="absolute left-[17px] top-2 bottom-2 w-px bg-[#1a1a24]" />
          <div className="space-y-0">
            {events.map((e, i) => (
              <button
                key={`${e.event_type}-${e.id}-${i}`}
                onClick={() => handleClick(e)}
                className="w-full flex items-start gap-4 py-3 pl-0 pr-4 text-left hover:bg-[#0d1117]/50 rounded-xl transition-all group"
              >
                <div className="relative z-10 w-9 h-9 rounded-full bg-[#0a0a0f] border-2 border-[#1a1a24] flex items-center justify-center flex-shrink-0">
                  {getIcon(e.event_type)}
                </div>
                <div className="flex-1 min-w-0 pt-0.5">
                  <div className="flex items-center justify-between gap-2">
                    <p className="text-sm text-white font-medium truncate">
                      {e.event_type === "milestone" && (e.name || "Milestone updated")}
                      {e.event_type === "invoice" && `${e.invoice_number || "Invoice"} — ${e.currency || ""} ${Number(e.total_amount || 0).toLocaleString()}`}
                      {e.event_type === "ticket" && (e.title || "Ticket created")}
                    </p>
                    <span className="text-[11px] text-[#6a6a75] flex-shrink-0">{formatDate(e.date)}</span>
                  </div>
                  <div className="flex items-center gap-2 mt-0.5">
                    <span className={`text-[11px] capitalize ${getStatusColor(e.event_type, e.status || e.status_name || "")}`}>
                      {(e.status || e.status_name || "updated").replace("_", " ")}
                    </span>
                    {e.event_type === "milestone" && e.project_name && (
                      <>
                        <span className="text-[#2a2a35] text-[10px]">•</span>
                        <span className="text-[11px] text-[#6a6a75] truncate">{e.project_name}</span>
                      </>
                    )}
                  </div>
                </div>
                <ChevronRight className="h-4 w-4 text-[#2a2a35] group-hover:text-[#1BB0CE] transition-colors flex-shrink-0 mt-1" />
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
