"use client"

import { useState, useEffect, useCallback } from "react"
import { useRouter } from "next/navigation"
import { PageHeader } from "@/components/shared/page-header"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Card } from "@/components/ui/card"
import { GripVertical, Plus, User, Building2, Mail, Phone, Hash } from "lucide-react"

interface KanbanLead {
  id: string
  company_name: string
  contact_name: string
  email: string
  phone: string
  score: number
  notes: string
  assigned_to: string | null
  created_at: string
}

interface KanbanColumn {
  id: string
  name: string
  status: string
  sortOrder: number
  probability: number
  leads: KanbanLead[]
}

const statusColors: Record<string, { header: string; border: string; dot: string }> = {
  open: { header: "bg-blue-500/10 border-blue-500/20", border: "border-blue-500/20", dot: "bg-blue-500" },
  contacted: { header: "bg-amber-500/10 border-amber-500/20", border: "border-amber-500/20", dot: "bg-amber-500" },
  pending: { header: "bg-purple-500/10 border-purple-500/20", border: "border-purple-500/20", dot: "bg-purple-500" },
  closed: { header: "bg-emerald-500/10 border-emerald-500/20", border: "border-emerald-500/20", dot: "bg-emerald-500" },
  ignored: { header: "bg-zinc-500/10 border-zinc-500/20", border: "border-zinc-500/20", dot: "bg-zinc-500" },
}

const columnGradient: Record<string, string> = {
  open: "from-blue-500/5",
  contacted: "from-amber-500/5",
  pending: "from-purple-500/5",
  closed: "from-emerald-500/5",
  ignored: "from-zinc-500/5",
}

export default function KanbanPage() {
  const router = useRouter()
  const [columns, setColumns] = useState<KanbanColumn[]>([])
  const [loading, setLoading] = useState(true)
  const [draggedLead, setDraggedLead] = useState<{ leadId: string; fromStatus: string } | null>(null)

  const fetchKanban = useCallback(async () => {
    try {
      const res = await fetch("/api/leads/kanban")
      const data = await res.json()
      setColumns(data)
    } catch (e) {
      console.error("Failed to load kanban", e)
    } finally {
      setLoading(false)
    }
  }, [])

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

  const handleDragStart = (leadId: string, status: string) => {
    setDraggedLead({ leadId, fromStatus: status })
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
  }

  const handleDrop = async (toStatus: string) => {
    if (!draggedLead || draggedLead.fromStatus === toStatus) {
      setDraggedLead(null)
      return
    }

    setColumns((prev) => {
      const next = prev.map((col) => ({ ...col, leads: [...col.leads] }))
      const fromCol = next.find((c) => c.status === draggedLead.fromStatus)
      const toCol = next.find((c) => c.status === toStatus)
      if (!fromCol || !toCol) return prev
      const leadIdx = fromCol.leads.findIndex((l) => l.id === draggedLead.leadId)
      if (leadIdx === -1) return prev
      const [moved] = fromCol.leads.splice(leadIdx, 1)
      toCol.leads.unshift(moved)
      return next
    })

    try {
      await fetch(`/api/leads/${draggedLead.leadId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: toStatus }),
      })
    } catch (e) {
      console.error("Failed to update lead status", e)
      fetchKanban()
    }
    setDraggedLead(null)
  }

  if (loading) {
    return (
      <div className="space-y-4">
        <PageHeader title="Kanban Board" description="Drag and drop leads to update their stage" />
        <div className="flex gap-4 overflow-x-auto pb-4">
          {[1, 2, 3, 4, 5].map((i) => (
            <div key={i} className="flex h-96 w-72 shrink-0 animate-pulse rounded-lg bg-muted" />
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      <PageHeader
        title="Kanban Board"
        description="Drag and drop leads between stages to update their status"
      >
        <Button variant="outline" size="sm" onClick={() => router.push("/leads")}>
          Table View
        </Button>
        <Button size="sm" onClick={() => router.push("/leads/new")}>
          <Plus className="mr-1.5 h-4 w-4" /> New Lead
        </Button>
      </PageHeader>

      <div className="flex gap-4 overflow-x-auto pb-4" style={{ minHeight: "calc(100vh - 12rem)" }}>
        {columns.map((col) => {
          const colors = statusColors[col.status] || statusColors.open
          return (
            <div
              key={col.id}
              className="flex w-72 shrink-0 flex-col rounded-lg border bg-card"
              onDragOver={handleDragOver}
              onDrop={() => handleDrop(col.status)}
            >
              <div className={`flex items-center justify-between rounded-t-lg border-b px-3 py-2.5 ${colors.header}`}>
                <div className="flex items-center gap-2">
                  <span className={`h-2 w-2 rounded-full ${colors.dot}`} />
                  <span className="text-sm font-semibold">{col.name}</span>
                  <span className="text-xs text-muted-foreground">({col.leads.length})</span>
                </div>
                {col.probability > 0 && (
                  <span className="text-xs text-muted-foreground">{col.probability}%</span>
                )}
              </div>

              <div className="flex-1 space-y-2 overflow-y-auto p-2">
                {col.leads.length === 0 && (
                  <div className="flex h-20 items-center justify-center">
                    <p className="text-xs text-muted-foreground">No leads</p>
                  </div>
                )}
                {col.leads.map((lead) => (
                  <LeadCard
                    key={lead.id}
                    lead={lead}
                    status={col.status}
                    onDragStart={handleDragStart}
                    onClick={() => router.push(`/leads/${lead.id}`)}
                  />
                ))}
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

function LeadCard({
  lead,
  status,
  onDragStart,
  onClick,
}: {
  lead: KanbanLead
  status: string
  onDragStart: (id: string, status: string) => void
  onClick: () => void
}) {
  const initials = lead.contact_name
    ?.split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()

  return (
    <Card
      draggable
      onDragStart={() => onDragStart(lead.id, status)}
      onClick={onClick}
      className="cursor-grab active:cursor-grabbing p-3 space-y-2 transition-shadow hover:shadow-md"
    >
      <div className="flex items-start justify-between gap-2">
        <div className="flex items-center gap-2 min-w-0">
          <Avatar className="h-7 w-7 shrink-0">
            <AvatarFallback className="text-[10px]">{initials}</AvatarFallback>
          </Avatar>
          <div className="min-w-0">
            <p className="text-sm font-medium truncate">{lead.contact_name}</p>
            {lead.company_name && (
              <p className="flex items-center gap-1 text-xs text-muted-foreground truncate">
                <Building2 className="h-3 w-3 shrink-0" />
                {lead.company_name}
              </p>
            )}
          </div>
        </div>
        <GripVertical className="h-4 w-4 shrink-0 text-muted-foreground/40" />
      </div>

      <div className="space-y-1">
        {lead.email && (
          <p className="flex items-center gap-1.5 text-xs text-muted-foreground truncate">
            <Mail className="h-3 w-3 shrink-0" />
            {lead.email}
          </p>
        )}
        {lead.phone && (
          <p className="flex items-center gap-1.5 text-xs text-muted-foreground truncate">
            <Phone className="h-3 w-3 shrink-0" />
            {lead.phone}
          </p>
        )}
      </div>

      {lead.score > 0 && (
        <div className="flex items-center gap-1.5">
          <Hash className="h-3 w-3 text-muted-foreground/60" />
          <div className="flex h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
            <div
              className="rounded-full transition-all"
              style={{
                width: `${lead.score}%`,
                backgroundColor:
                  lead.score >= 70 ? "#22c55e" : lead.score >= 40 ? "#eab308" : "#ef4444",
              }}
            />
          </div>
          <span className="text-[11px] text-muted-foreground">{lead.score}</span>
        </div>
      )}
    </Card>
  )
}
