"use client"

import { useState, useMemo } 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 { leads } from "@/data/leads"
import { filterLeadsByPeriod } from "@/lib/date-utils"

export default function LeadsPage() {
  const router = useRouter()
  const [search, setSearch] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [periodFilter, setPeriodFilter] = useState("all")

  const filteredLeads = useMemo(() => {
    let result = leads

    if (periodFilter && periodFilter !== "all") {
      result = filterLeadsByPeriod(result, periodFilter)
    }

    if (search) {
      const q = search.toLowerCase()
      result = result.filter(
        (l) =>
          l.companyName.toLowerCase().includes(q) ||
          l.contactName.toLowerCase().includes(q) ||
          l.email.toLowerCase().includes(q) ||
          l.phone.includes(q)
      )
    }

    if (statusFilter && statusFilter !== "all") {
      result = result.filter((l) => l.status === statusFilter)
    }

    return result
  }, [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={filteredLeads} />
      </div>
    </div>
  )
}
