// ───────────────────────────────────────────────
// Leads List Page (/(dashboard)/leads)
// ───────────────────────────────────────────────
// Route: /leads
// Purpose: List, search, filter, and navigate to
//   leads. Supports status/period filters and a
//   text search. "Create" button navigates to
//   /leads/new.
// Layout: PageHeader + toolbar (search + filters)
//   + LeadsTable.
// ───────────────────────────────────────────────

"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"

/**
 * LeadsPage
 * ─────────
 * Fetches leads from the API whenever search,
 * status, or period filters change. Passes data
 * and loading state to the table and toolbar.
 *
 * @returns Leads list layout.
 */
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)

  // ── Fetch leads with current filters ──
  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"
      />

      {/* ── Toolbar + Table ── */}
      <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>
  )
}
