"use client";

import React, { useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Plus,
  Search,
  Building2,
  MapPin,
  Filter,
} from "lucide-react";
import { useApiData } from "@/hooks/use-api-data";
import { mockSellerLeads, mockMatches } from "@/lib/mock-data";
import { formatCurrency, formatNumber, formatDate, getStatusColor, ASSET_TYPES } from "@/lib/utils";
import type { SellerLead, Match } from "@/types";

export default function SellersPage() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState("all");
  const [filterStatus, setFilterStatus] = useState("all");

  const { data: apiSellers } = useApiData<SellerLead[]>('/api/sellers', []);
  const { data: apiMatches } = useApiData<Match[]>('/api/matches', []);

  const allSellers = apiSellers.length > 0 ? apiSellers : mockSellerLeads;
  const allMatches = apiMatches.length > 0 ? apiMatches : mockMatches;

  const filteredLeads = allSellers.filter((lead) => {
    const matchesSearch =
      lead.address.toLowerCase().includes(searchTerm.toLowerCase()) ||
      lead.market.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = filterType === "all" || lead.asset_type === filterType;
    const matchesStatus = filterStatus === "all" || lead.status === filterStatus;
    return matchesSearch && matchesType && matchesStatus;
  });

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-navy-900">Seller Leads</h1>
          <p className="text-sm text-navy-500 mt-1">
            {allSellers.length} total leads • {allSellers.filter((l) => l.status === "active").length} active
          </p>
        </div>
        <Link href="/dashboard/sellers/new" className="w-full sm:w-auto">
          <Button variant="gold" className="w-full sm:w-auto">
            <Plus className="mr-2 h-4 w-4" />
            Add New Lead
          </Button>
        </Link>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-navy-400" />
          <Input
            placeholder="Search by address or market..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={filterType} onValueChange={setFilterType}>
          <SelectTrigger className="w-full sm:w-44">
            <Filter className="h-4 w-4 mr-2" />
            <SelectValue placeholder="Asset Type" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Types</SelectItem>
            {ASSET_TYPES.map((type) => (
              <SelectItem key={type} value={type}>
                {type}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={filterStatus} onValueChange={setFilterStatus}>
          <SelectTrigger className="w-full sm:w-40">
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Status</SelectItem>
            <SelectItem value="active">Active</SelectItem>
            <SelectItem value="pending">Pending</SelectItem>
            <SelectItem value="matched">Matched</SelectItem>
            <SelectItem value="closed">Closed</SelectItem>
            <SelectItem value="withdrawn">Withdrawn</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Leads Table */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto -mx-px">
            <table className="w-full min-w-[800px]">
              <thead>
                <tr className="border-b border-navy-100">
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Property
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Type
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Price
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Cap Rate
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Size
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Matches
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Status
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Date
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-navy-50">
                {filteredLeads.map((lead) => {
                  const matchCount = allMatches.filter(
                    (m) => m.lead_id === lead.id
                  ).length;

                  return (
                    <tr key={lead.id} className="hover:bg-navy-25 transition-colors group">
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-3">
                          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-navy-50 group-hover:bg-gold-50 transition-colors">
                            <Building2 className="h-4 w-4 text-navy-600 group-hover:text-gold-600 transition-colors" />
                          </div>
                          <div>
                            <p className="text-sm font-medium text-navy-900">{lead.address}</p>
                            <div className="flex items-center gap-1 text-xs text-navy-500">
                              <MapPin className="h-3 w-3" />
                              {lead.market}
                            </div>
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm text-navy-700">{lead.asset_type}</span>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm font-semibold text-navy-900">
                          {formatCurrency(lead.asking_price)}
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm text-navy-700">
                          {lead.cap_rate ? `${lead.cap_rate}%` : "—"}
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm text-navy-700">
                          {lead.sqft ? `${formatNumber(lead.sqft)} SF` : "—"}
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm font-medium text-navy-700">{matchCount}</span>
                      </td>
                      <td className="px-6 py-4">
                        <Badge className={getStatusColor(lead.status)} variant="secondary">
                          {lead.status}
                        </Badge>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-xs text-navy-500">{formatDate(lead.created_at)}</span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {filteredLeads.length === 0 && (
            <div className="text-center py-12">
              <p className="text-sm text-navy-500">No leads match your filters.</p>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
