"use client";

import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  Target,
  Building2,
  ArrowRight,
  Send,
  Check,
  X,
  Search,
  Filter,
} from "lucide-react";
import { useApiData } from "@/hooks/use-api-data";
import { mockMatches } from "@/lib/mock-data";
import { formatCurrency, getInitials, getStatusColor, formatRelativeTime } from "@/lib/utils";
import { getMatchQuality } from "@/lib/matching";
import type { Match } from "@/types";

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

  const { data: apiMatches } = useApiData<Match[]>('/api/matches', []);
  const allMatches = apiMatches.length > 0 ? apiMatches : mockMatches;

  const filteredMatches = allMatches.filter((match) => {
    const matchesSearch =
      (match.seller_lead?.address || "").toLowerCase().includes(searchTerm.toLowerCase()) ||
      (match.buyer?.name || "").toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = filterStatus === "all" || match.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  const pendingCount = allMatches.filter((m) => m.status === "pending").length;
  const sentCount = allMatches.filter((m) => m.status === "sent").length;
  const interestedCount = allMatches.filter((m) => m.status === "interested").length;

  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">Matches</h1>
          <p className="text-sm text-navy-500 mt-1">
            AI-powered buyer-seller matches ranked by compatibility
          </p>
        </div>
        <div className="flex items-center gap-3 overflow-x-auto">
          <div className="flex items-center gap-2 sm:gap-3 text-xs sm:text-sm whitespace-nowrap">
            <span className="flex items-center gap-1.5">
              <div className="h-2 w-2 rounded-full bg-amber-500" />
              <span className="text-navy-500">{pendingCount} Pending</span>
            </span>
            <span className="flex items-center gap-1.5">
              <div className="h-2 w-2 rounded-full bg-blue-500" />
              <span className="text-navy-500">{sentCount} Sent</span>
            </span>
            <span className="flex items-center gap-1.5">
              <div className="h-2 w-2 rounded-full bg-emerald-500" />
              <span className="text-navy-500">{interestedCount} Interested</span>
            </span>
          </div>
        </div>
      </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 property or buyer..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={filterStatus} onValueChange={setFilterStatus}>
          <SelectTrigger className="w-full sm:w-44">
            <Filter className="h-4 w-4 mr-2" />
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Matches</SelectItem>
            <SelectItem value="pending">Pending Review</SelectItem>
            <SelectItem value="approved">Approved</SelectItem>
            <SelectItem value="sent">Sent</SelectItem>
            <SelectItem value="interested">Interested</SelectItem>
            <SelectItem value="passed">Passed</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Matches List */}
      <div className="space-y-4">
        {filteredMatches.map((match) => {
          const quality = getMatchQuality(match.match_score);

          return (
            <Card key={match.id} className="hover:shadow-md transition-shadow">
              <CardContent className="p-5">
                <div className="flex flex-col lg:flex-row lg:items-center gap-4">
                  {/* Seller Lead */}
                  <div className="flex-1">
                    <p className="text-xs text-navy-400 uppercase tracking-wider font-medium mb-1.5">
                      Seller Lead
                    </p>
                    <div className="flex items-center gap-3">
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-navy-50">
                        <Building2 className="h-5 w-5 text-navy-600" />
                      </div>
                      <div>
                        <p className="text-sm font-semibold text-navy-900">
                          {match.seller_lead?.address}
                        </p>
                        <p className="text-xs text-navy-500">
                          {match.seller_lead?.asset_type} •{" "}
                          {match.seller_lead?.market} •{" "}
                          {match.seller_lead ? formatCurrency(match.seller_lead.asking_price) : "N/A"}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Match Score */}
                  <div className="flex items-center gap-3 lg:flex-col lg:items-center px-4">
                    <ArrowRight className="h-4 w-4 text-navy-300 hidden lg:block" />
                    <div className="flex flex-col items-center">
                      <Target className="h-4 w-4 text-gold-500 mb-1" />
                      <span className={`text-xl font-bold ${quality.color}`}>
                        {match.match_score}%
                      </span>
                      <span className="text-xs text-navy-400">{quality.label}</span>
                    </div>
                    <ArrowRight className="h-4 w-4 text-navy-300 hidden lg:block" />
                  </div>

                  {/* Buyer */}
                  <div className="flex-1">
                    <p className="text-xs text-navy-400 uppercase tracking-wider font-medium mb-1.5">
                      Buyer
                    </p>
                    <div className="flex items-center gap-3">
                      <Avatar className="h-10 w-10">
                        <AvatarFallback className="text-xs font-semibold bg-navy-100 text-navy-700">
                          {match.buyer ? getInitials(match.buyer.name) : "??"}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <p className="text-sm font-semibold text-navy-900">
                          {match.buyer?.name}
                        </p>
                        <p className="text-xs text-navy-500">
                          {match.buyer?.company} • {match.buyer?.email}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-2 lg:flex-col flex-wrap">
                    <Badge className={getStatusColor(match.status)} variant="secondary">
                      {match.status}
                    </Badge>
                    <div className="flex gap-1">
                      {match.status === "pending" && (
                        <>
                          <Button variant="gold" size="sm" className="min-h-[44px] sm:min-h-0">
                            <Send className="mr-1 h-3.5 w-3.5" />
                            Send
                          </Button>
                          <Button variant="ghost" size="sm" className="min-h-[44px] sm:min-h-0">
                            <X className="h-3.5 w-3.5" />
                          </Button>
                        </>
                      )}
                      {match.status === "sent" && (
                        <span className="text-xs text-navy-400">
                          Sent {formatRelativeTime(match.updated_at)}
                        </span>
                      )}
                      {match.status === "interested" && (
                        <Button variant="outline" size="sm" className="min-h-[44px] sm:min-h-0">
                          <Check className="mr-1 h-3.5 w-3.5" />
                          Follow Up
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      {filteredMatches.length === 0 && (
        <div className="text-center py-12">
          <Target className="h-12 w-12 text-navy-300 mx-auto mb-4" />
          <p className="text-sm text-navy-500">No matches found. Try adjusting your filters.</p>
        </div>
      )}
    </div>
  );
}
