"use client";

import React from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import {
  ArrowLeft,
  Mail,
  Phone,
  Building2,
  MapPin,
  Send,
  Edit,
} from "lucide-react";
import { useApiData } from "@/hooks/use-api-data";
import { mockBuyers, mockMatches, mockOutreach } from "@/lib/mock-data";
import {
  formatCurrency,
  formatDate,
  formatRelativeTime,
  getInitials,
  getStatusColor,
} from "@/lib/utils";
import { getMatchQuality } from "@/lib/matching";
import type { Buyer, Match, Outreach } from "@/types";

export default function BuyerDetailPage({ params }: { params: { id: string } }) {
  const { data: apiBuyer } = useApiData<Buyer | null>(`/api/buyers/${params.id}`, null);
  const { data: apiMatches } = useApiData<Match[]>('/api/matches', []);
  const { data: apiOutreach } = useApiData<Outreach[]>('/api/outreach', []);

  const buyer = apiBuyer || mockBuyers.find((b) => b.id === params.id) || mockBuyers[0];
  const allMatches = apiMatches.length > 0 ? apiMatches : mockMatches;
  const allOutreach = apiOutreach.length > 0 ? apiOutreach : mockOutreach;

  const buyerMatches = allMatches.filter((m) => m.buyer_id === buyer.id);
  const buyerOutreach = allOutreach.filter((o) =>
    buyerMatches.some((m) => m.id === o.match_id)
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <Link
          href="/dashboard/buyers"
          className="inline-flex items-center gap-1 text-sm text-navy-500 hover:text-navy-700 mb-4 transition-colors"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to Buyers
        </Link>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Info */}
        <div className="lg:col-span-2 space-y-6">
          {/* Profile Card */}
          <Card>
            <CardContent className="p-6">
              <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4 mb-6">
                <div className="flex items-center gap-3 sm:gap-4">
                  <Avatar className="h-12 w-12 sm:h-16 sm:w-16">
                    <AvatarFallback className="text-base sm:text-lg font-semibold bg-navy-100 text-navy-700">
                      {getInitials(buyer.name)}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <h1 className="text-lg sm:text-xl font-bold text-navy-900">{buyer.name}</h1>
                    {buyer.company && (
                      <p className="text-sm text-navy-500">{buyer.company}</p>
                    )}
                    <Badge className={`mt-2 ${getStatusColor(buyer.status)}`} variant="secondary">
                      {buyer.status}
                    </Badge>
                  </div>
                </div>
                <Button variant="outline" size="sm" className="w-full sm:w-auto">
                  <Edit className="mr-2 h-3.5 w-3.5" />
                  Edit
                </Button>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="flex items-center gap-3 p-3 rounded-lg bg-navy-50">
                  <Mail className="h-4 w-4 text-navy-500" />
                  <div>
                    <p className="text-xs text-navy-400">Email</p>
                    <p className="text-sm text-navy-900">{buyer.email}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3 p-3 rounded-lg bg-navy-50">
                  <Phone className="h-4 w-4 text-navy-500" />
                  <div>
                    <p className="text-xs text-navy-400">Phone</p>
                    <p className="text-sm text-navy-900">{buyer.phone || "Not provided"}</p>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Acquisition Criteria */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Acquisition Criteria</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <p className="text-xs text-navy-400 mb-1.5">Target Asset Types</p>
                  <div className="flex flex-wrap gap-1.5">
                    {buyer.asset_types.map((type) => (
                      <Badge key={type} variant="secondary">
                        <Building2 className="mr-1 h-3 w-3" />
                        {type}
                      </Badge>
                    ))}
                  </div>
                </div>
                <div>
                  <p className="text-xs text-navy-400 mb-1.5">Target Locations</p>
                  <div className="flex flex-wrap gap-1.5">
                    {buyer.target_locations.map((loc) => (
                      <Badge key={loc} variant="outline">
                        <MapPin className="mr-1 h-3 w-3" />
                        {loc}
                      </Badge>
                    ))}
                  </div>
                </div>
              </div>

              <Separator />

              <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 sm:gap-4">
                <div>
                  <p className="text-xs text-navy-400">Min Price</p>
                  <p className="text-sm font-semibold text-navy-900">
                    {buyer.price_min ? formatCurrency(buyer.price_min) : "Any"}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-navy-400">Max Price</p>
                  <p className="text-sm font-semibold text-navy-900">
                    {buyer.price_max ? formatCurrency(buyer.price_max) : "No Max"}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-navy-400">Min Cap Rate</p>
                  <p className="text-sm font-semibold text-navy-900">
                    {buyer.cap_rate_min ? `${buyer.cap_rate_min}%` : "Any"}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-navy-400">Max Cap Rate</p>
                  <p className="text-sm font-semibold text-navy-900">
                    {buyer.cap_rate_max ? `${buyer.cap_rate_max}%` : "Any"}
                  </p>
                </div>
              </div>

              {buyer.preferences && (
                <>
                  <Separator />
                  <div>
                    <p className="text-xs text-navy-400 mb-1">Additional Preferences</p>
                    <p className="text-sm text-navy-700">{buyer.preferences}</p>
                  </div>
                </>
              )}
            </CardContent>
          </Card>

          {/* Deal Matches */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Building2 className="h-5 w-5 text-gold-500" />
                Deal Matches ({buyerMatches.length})
              </CardTitle>
            </CardHeader>
            <CardContent>
              {buyerMatches.length > 0 ? (
                <div className="space-y-3">
                  {buyerMatches.map((match) => {
                    const quality = getMatchQuality(match.match_score);
                    return (
                      <div
                        key={match.id}
                        className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 p-3 rounded-lg border border-navy-100 hover:border-navy-200 transition-colors"
                      >
                        <div className="flex items-center gap-3">
                          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-navy-50 flex-shrink-0">
                            <Building2 className="h-4 w-4 text-navy-600" />
                          </div>
                          <div className="min-w-0">
                            <p className="text-sm font-medium text-navy-900 truncate">
                              {match.seller_lead?.address || "Property"}
                            </p>
                            <p className="text-xs text-navy-500">
                              {match.seller_lead?.asset_type} • {match.seller_lead?.market}
                            </p>
                          </div>
                        </div>
                        <div className="flex items-center gap-4 ml-12 sm:ml-0">
                          <div className="text-right">
                            <p className={`text-sm font-bold ${quality.color}`}>
                              {match.match_score}%
                            </p>
                            <p className="text-xs text-navy-400">{quality.label}</p>
                          </div>
                          <Badge className={getStatusColor(match.status)} variant="secondary">
                            {match.status}
                          </Badge>
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <p className="text-sm text-navy-500 text-center py-6">
                  No matches yet. Add a seller lead to start matching.
                </p>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Engagement Score */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-semibold">Engagement Score</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-center mb-4">
                <span className="text-4xl font-bold text-navy-900">{buyer.engagement_score}</span>
                <span className="text-lg text-navy-400">/100</span>
              </div>
              <Progress value={buyer.engagement_score} className="h-2 mb-4" />
              <div className="space-y-2 text-xs">
                <div className="flex justify-between text-navy-500">
                  <span>Last Contacted</span>
                  <span className="font-medium text-navy-700">
                    {buyer.last_contacted_at
                      ? formatRelativeTime(buyer.last_contacted_at)
                      : "Never"}
                  </span>
                </div>
                <div className="flex justify-between text-navy-500">
                  <span>Added</span>
                  <span className="font-medium text-navy-700">
                    {formatDate(buyer.created_at)}
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Outreach History */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm font-semibold flex items-center gap-2">
                <Send className="h-4 w-4 text-navy-500" />
                Outreach History
              </CardTitle>
            </CardHeader>
            <CardContent>
              {buyerOutreach.length > 0 ? (
                <div className="space-y-3">
                  {buyerOutreach.map((item) => (
                    <div key={item.id} className="flex items-start gap-2">
                      <div className="mt-1">
                        {item.channel === "email" ? (
                          <Mail className="h-3.5 w-3.5 text-navy-400" />
                        ) : (
                          <Phone className="h-3.5 w-3.5 text-navy-400" />
                        )}
                      </div>
                      <div className="flex-1">
                        <p className="text-xs text-navy-700">
                          {item.subject || item.body.slice(0, 50) + "..."}
                        </p>
                        <div className="flex items-center gap-2 mt-0.5">
                          <Badge
                            className={`text-[10px] ${getStatusColor(item.status)}`}
                            variant="secondary"
                          >
                            {item.status}
                          </Badge>
                          <span className="text-[10px] text-navy-400">
                            {item.sent_at ? formatRelativeTime(item.sent_at) : "Draft"}
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-xs text-navy-500 text-center py-4">No outreach yet</p>
              )}
            </CardContent>
          </Card>

          {/* Quick Actions */}
          <Card>
            <CardContent className="pt-6 space-y-2">
              <Button variant="gold" className="w-full" size="sm">
                <Send className="mr-2 h-3.5 w-3.5" />
                Send Deals
              </Button>
              <Button variant="outline" className="w-full" size="sm">
                <Mail className="mr-2 h-3.5 w-3.5" />
                Email Buyer
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
