"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { PageHeader } from "@/components/shared/page-header"
import { LeadsTable } from "@/components/leads/leads-table"
import { LeadsTableToolbar } from "@/components/leads/leads-table-toolbar"
import { Lead } from "@/types"

export default function LeadsPage() {
  const router = useRouter()
  const [search, setSearch] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [periodFilter, setPeriodFilter] = useState("all")
  const [leadsData, setLeadsData] = useState<Lead[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const params = new URLSearchParams()
    if (search) params.set("search", search)
    if (statusFilter !== "all") params.set("status", statusFilter)
    if (periodFilter !== "all") params.set("period", periodFilter)

    setLoading(true)
    fetch(`/api/leads?${params.toString()}`)
      .then((r) => r.json())
      .then((data) => {
        setLeadsData(data)
        setLoading(false)
      })
      .catch(() => setLoading(false))
  }, [search, statusFilter, periodFilter])

  return (
    <div className="space-y-4">
      <PageHeader
        title="Leads"
        description="Manage and track your sales leads"
      />

      <div className="rounded-lg border bg-card">
        <div className="p-4">
          <LeadsTableToolbar
            search={search}
            onSearchChange={setSearch}
            statusFilter={statusFilter}
            onStatusFilterChange={setStatusFilter}
            periodFilter={periodFilter}
            onPeriodFilterChange={setPeriodFilter}
            onCreateClick={() => router.push("/leads/new")}
          />
        </div>
        <LeadsTable data={leadsData} loading={loading} />
      </div>
    </div>
  )
}
