"use client"

import { useState, useMemo } from "react"
import { PageHeader } from "@/components/shared/page-header"
import { LeadsTable } from "@/components/leads/leads-table"
import { LeadsTableToolbar } from "@/components/leads/leads-table-toolbar"
import { LeadFormDialog } from "@/components/leads/lead-form-dialog"
import { leads } from "@/data/leads"
import { filterLeadsByPeriod } from "@/lib/date-utils"

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

  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={() => setCreateOpen(true)}
          />
        </div>
        <LeadsTable data={filteredLeads} />
      </div>

      <LeadFormDialog open={createOpen} onOpenChange={setCreateOpen} />
    </div>
  )
}
