"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { PageHeader } from "@/components/shared/page-header"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card } from "@/components/ui/card"
import { Search, Plus, ArrowRight, FileText, Calendar, User } from "lucide-react"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

export default function ProposalsPage() {
  const router = useRouter()
  const [proposals, setProposals] = useState<any[]>([])
  const [statuses, setStatuses] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")

  useEffect(() => {
    const params = new URLSearchParams()
    if (search) params.set("search", search)
    if (statusFilter !== "all") params.set("status", statusFilter)
    fetch(`/api/proposals?${params}`)
      .then((r) => r.json())
      .then(setProposals)
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [search, statusFilter])

  useEffect(() => {
    fetch("/api/proposal-statuses").then((r) => r.json()).then(setStatuses).catch(() => {})
  }, [])

  const formatCurrency = (n: number) => n ? `R${Number(n).toLocaleString()}` : "R0"

  return (
    <div className="space-y-4">
      <PageHeader title="Proposals & Quotes" description="Create and send professional quotes to clients">
        <Button size="sm" onClick={() => router.push("/proposals/new")}>
          <Plus className="mr-1.5 h-4 w-4" /> New Proposal
        </Button>
      </PageHeader>

      <Card>
        <div className="p-4">
          <div className="flex flex-1 flex-col gap-4 sm:flex-row sm:items-center">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Search proposals..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="h-9 pl-9 w-full sm:max-w-sm"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="h-9 w-[160px]">
                <SelectValue placeholder="All Statuses" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Statuses</SelectItem>
                {statuses.map((s: any) => (
                  <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="divide-y">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : proposals.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">No proposals yet</div>
          ) : (
            proposals.map((p: any) => (
              <div
                key={p.id}
                className="flex items-center gap-4 px-6 py-4 hover:bg-muted/50 cursor-pointer transition-colors"
                onClick={() => router.push(`/proposals/${p.id}`)}
              >
                <FileText className="h-5 w-5 text-muted-foreground shrink-0" />
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-medium truncate">{p.title}</span>
                    <Badge variant="outline" className="shrink-0 text-xs" style={{ borderColor: p.status_color + "40", color: p.status_color }}>
                      {p.status_name}
                    </Badge>
                  </div>
                  <div className="flex items-center gap-4 mt-1 text-sm text-muted-foreground">
                    <span className="flex items-center gap-1"><User className="h-3.5 w-3.5" />{p.created_by_name}</span>
                    <span>{p.proposal_number}</span>
                    <span className="font-medium">{formatCurrency(p.total_amount)}</span>
                    {p.valid_until && (
                      <span className="flex items-center gap-1"><Calendar className="h-3.5 w-3.5" />Valid until {new Date(p.valid_until).toLocaleDateString()}</span>
                    )}
                  </div>
                </div>
                <ArrowRight className="h-4 w-4 text-muted-foreground shrink-0" />
              </div>
            ))
          )}
        </div>
      </Card>
    </div>
  )
}
