import { useEffect, useState, useCallback, type FormEvent } from 'react';
import {
  Building2,
  Search,
  Users,
  Send,
  CheckCircle2,
  XCircle,
  Clock,
  History,
  DollarSign,
  Target,
  BarChart3,
  Eye,
  Activity,
  Handshake,
  Save,
  MessageSquare,
  MapPin,
} from 'lucide-react';
import { DashboardLayout } from '../../components/layout/DashboardLayout';
import { StatCard } from '../../components/ui/StatCard';
import { Card, CardHeader, CardTitle } from '../../components/ui/Card';
import { Badge } from '../../components/ui/Badge';
import { Button } from '../../components/ui/Button';
import { Input, Textarea } from '../../components/ui/Input';
import { EmptyState } from '../../components/ui/EmptyState';
import { Loading } from '../../components/ui/Loading';
import { Modal } from '../../components/ui/Modal';
import { AccountSettingsPanel } from '../../components/profile/AccountSettingsPanel';
import { businessService } from '../../services/business';
import { collaborationService } from '../../services/collaboration';
import { handleApiError } from '../../services/api';
import type { BusinessProfile, MatchingResponse, InfluencerMatch, BusinessSearch } from '../../types/business';
import type { CollaborationRequest } from '../../types/collaboration';

function formatNumber(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return n.toLocaleString();
}

/** Target audience geography for Find Creators (not company HQ). */
const TARGET_AUDIENCE_COUNTRIES = ['Pakistan'] as const;
const TARGET_AUDIENCE_CITIES = [
  'Karachi',
  'Rawalpindi',
  'Hyderabad',
  'Lahore',
  'Islamabad',
  'Peshawar',
  'Quetta',
] as const;

function toggleAudienceItem(list: string[], item: string, checked: boolean): string[] {
  if (checked) {
    return list.includes(item) ? list : [...list, item];
  }
  return list.filter((x) => x !== item);
}

export default function BusinessDashboard() {
  const [profile, setProfile] = useState<BusinessProfile | null>(null);
  const [collabs, setCollabs] = useState<CollaborationRequest[]>([]);
  const [history, setHistory] = useState<BusinessSearch[]>([]);
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState('');

  // Profile form state
  const [profileForm, setProfileForm] = useState({
    company_name: '',
    industry: '',
    company_description: '',
    company_website: '',
    contact_email: '',
    contact_phone: '',
    country: '',
    city: '',
    typical_budget_min: '',
    typical_budget_max: '',
  });
  const [profileSaving, setProfileSaving] = useState(false);

  // Match state
  const [matchForm, setMatchForm] = useState({
    business_description: '',
    budget_min: '',
    budget_max: '',
    audience_countries: [] as string[],
    audience_cities: [] as string[],
  });
  const [matching, setMatching] = useState(false);
  const [matchResults, setMatchResults] = useState<MatchingResponse | null>(null);

  // Collab request modal
  const [collabModal, setCollabModal] = useState<InfluencerMatch | null>(null);
  const [collabForm, setCollabForm] = useState({
    message: '',
    campaign_description: '',
    budget_offer: '',
  });
  const [sendingCollab, setSendingCollab] = useState(false);

  const showToast = useCallback((msg: string) => {
    setToast(msg);
    setTimeout(() => setToast(''), 5000);
  }, []);

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [p, c, h] = await Promise.allSettled([
        businessService.getProfile(),
        collaborationService.getBusinessCollaborations(),
        businessService.getSearchHistory(),
      ]);
      if (p.status === 'fulfilled' && p.value) {
        setProfile(p.value);
        setProfileForm({
          company_name: p.value.company_name || '',
          industry: p.value.industry || '',
          company_description: p.value.company_description || '',
          company_website: p.value.company_website || '',
          contact_email: p.value.contact_email || '',
          contact_phone: p.value.contact_phone || '',
          country: p.value.country || '',
          city: p.value.city || '',
          typical_budget_min: p.value.typical_budget_min?.toString() || '',
          typical_budget_max: p.value.typical_budget_max?.toString() || '',
        });
      }
      if (c.status === 'fulfilled') setCollabs(c.value);
      if (h.status === 'fulfilled') setHistory(h.value);
    } catch { /* handled per-call */ } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { loadData(); }, [loadData]);

  const handleProfileSave = async (e: FormEvent) => {
    e.preventDefault();
    setProfileSaving(true);
    try {
      const payload = {
        ...profileForm,
        typical_budget_min: profileForm.typical_budget_min ? Number(profileForm.typical_budget_min) : null,
        typical_budget_max: profileForm.typical_budget_max ? Number(profileForm.typical_budget_max) : null,
      };
      if (profile) {
        const updated = await businessService.updateProfile(profile.id, payload);
        setProfile(updated);
        showToast('Profile updated successfully.');
      } else {
        const created = await businessService.createProfile(payload);
        setProfile(created);
        showToast('Profile created successfully.');
      }
    } catch (err) {
      showToast(handleApiError(err));
    } finally {
      setProfileSaving(false);
    }
  };

  const handleMatch = async (e: FormEvent) => {
    e.preventDefault();
    setMatching(true);
    setMatchResults(null);
    try {
      const res = await businessService.matchInfluencers({
        business_description: matchForm.business_description,
        budget_min: Number(matchForm.budget_min),
        budget_max: Number(matchForm.budget_max),
        audience_countries: matchForm.audience_countries,
        audience_cities: matchForm.audience_cities,
      });
      setMatchResults(res);
      const h = await businessService.getSearchHistory();
      setHistory(h);
    } catch (err) {
      showToast(handleApiError(err));
    } finally {
      setMatching(false);
    }
  };

  const handleSendCollab = async () => {
    if (!collabModal) return;
    if (!profile) {
      showToast('Please create your business profile first (Overview tab).');
      return;
    }
    setSendingCollab(true);
    try {
      await collaborationService.sendCollaborationRequest({
        influencer: collabModal.profile.id,
        message: collabForm.message,
        campaign_description: collabForm.campaign_description,
        budget_offer: collabForm.budget_offer ? Number(collabForm.budget_offer) : null,
      });
      setCollabModal(null);
      setCollabForm({ message: '', campaign_description: '', budget_offer: '' });
      showToast('Collaboration request sent!');
      const c = await collaborationService.getBusinessCollaborations();
      setCollabs(c);
    } catch (err) {
      showToast(handleApiError(err));
    } finally {
      setSendingCollab(false);
    }
  };

  if (loading) return <Loading fullScreen text="Loading your dashboard..." />;

  const pendingCount = collabs.filter((c) => c.status === 'PENDING').length;
  const acceptedCount = collabs.filter((c) => c.status === 'ACCEPTED').length;

  return (
    <DashboardLayout defaultTab="overview">
      {(activeTab) => (
        <>
          {/* Toast */}
          {toast && (
            <div className="fixed top-4 right-4 z-50 px-4 py-3 rounded-lg bg-white border border-gray-200 text-sm text-gray-700 shadow-lg">
              {toast}
            </div>
          )}

          {/* OVERVIEW TAB */}
          {activeTab === 'overview' && (
            <div className="space-y-6">
              <div>
                <h1 className="text-2xl font-bold text-zinc-100">
                  {profile ? `Welcome, ${profile.company_name}` : 'Set Up Your Business'}
                </h1>
                <p className="text-sm text-zinc-500 mt-1">
                  {profile
                    ? 'Your business dashboard overview'
                    : 'Complete your profile to start finding creators'}
                </p>
              </div>

              {/* Quick stats */}
              {profile && (
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                  <StatCard
                    label="Total Searches"
                    value={history.length}
                    icon={<Search className="h-5 w-5" />}
                  />
                  <StatCard
                    label="Pending Requests"
                    value={pendingCount}
                    icon={<Clock className="h-5 w-5" />}
                  />
                  <StatCard
                    label="Active Collabs"
                    value={acceptedCount}
                    icon={<Handshake className="h-5 w-5" />}
                  />
                  <StatCard
                    label="Budget Range"
                    value={
                      profile.typical_budget_min && profile.typical_budget_max
                        ? `$${formatNumber(profile.typical_budget_min)} - $${formatNumber(profile.typical_budget_max)}`
                        : 'Not set'
                    }
                    icon={<DollarSign className="h-5 w-5" />}
                  />
                </div>
              )}

              {/* Profile form */}
              <Card>
                <CardHeader>
                  <CardTitle>
                    <div className="flex items-center gap-2">
                      <Building2 className="h-5 w-5 text-brand-400" />
                      Business Profile
                    </div>
                  </CardTitle>
                </CardHeader>
                <form onSubmit={handleProfileSave} className="space-y-4">
                  <div className="grid md:grid-cols-2 gap-4">
                    <Input
                      label="Company Name"
                      placeholder="Acme Inc."
                      value={profileForm.company_name}
                      onChange={(e) =>
                        setProfileForm({ ...profileForm, company_name: e.target.value })
                      }
                      required
                    />
                    <Input
                      label="Industry"
                      placeholder="e.g. Fashion, Tech, Food"
                      value={profileForm.industry}
                      onChange={(e) =>
                        setProfileForm({ ...profileForm, industry: e.target.value })
                      }
                    />
                  </div>
                  <Textarea
                    label="Company Description"
                    placeholder="Tell creators about your brand, products, and mission..."
                    rows={3}
                    value={profileForm.company_description}
                    onChange={(e) =>
                      setProfileForm({ ...profileForm, company_description: e.target.value })
                    }
                  />
                  <div className="grid md:grid-cols-2 gap-4">
                    <Input
                      label="Website"
                      type="url"
                      placeholder="https://example.com"
                      value={profileForm.company_website}
                      onChange={(e) =>
                        setProfileForm({ ...profileForm, company_website: e.target.value })
                      }
                    />
                    <Input
                      label="Contact Email"
                      type="email"
                      placeholder="hello@example.com"
                      value={profileForm.contact_email}
                      onChange={(e) =>
                        setProfileForm({ ...profileForm, contact_email: e.target.value })
                      }
                    />
                  </div>
                  <div className="grid md:grid-cols-2 gap-4">
                    <Input
                      label="Country"
                      placeholder="United States"
                      value={profileForm.country}
                      onChange={(e) =>
                        setProfileForm({ ...profileForm, country: e.target.value })
                      }
                    />
                    <Input
                      label="City"
                      placeholder="New York"
                      value={profileForm.city}
                      onChange={(e) =>
                        setProfileForm({ ...profileForm, city: e.target.value })
                      }
                    />
                  </div>
                  <div className="grid md:grid-cols-2 gap-4">
                    <Input
                      label="Typical Budget (Min)"
                      type="number"
                      placeholder="1000"
                      value={profileForm.typical_budget_min}
                      onChange={(e) =>
                        setProfileForm({ ...profileForm, typical_budget_min: e.target.value })
                      }
                    />
                    <Input
                      label="Typical Budget (Max)"
                      type="number"
                      placeholder="10000"
                      value={profileForm.typical_budget_max}
                      onChange={(e) =>
                        setProfileForm({ ...profileForm, typical_budget_max: e.target.value })
                      }
                    />
                  </div>
                  <div className="flex justify-end">
                    <Button
                      type="submit"
                      loading={profileSaving}
                      icon={<Save className="h-4 w-4" />}
                    >
                      {profile ? 'Update Profile' : 'Create Profile'}
                    </Button>
                  </div>
                </form>
              </Card>
            </div>
          )}

          {/* FIND CREATORS TAB */}
          {activeTab === 'find' && (
            <div className="space-y-6">
              <div>
                <h1 className="text-2xl font-bold text-zinc-100">
                  Find Creators
                </h1>
                <p className="text-sm text-zinc-500 mt-1">
                  Describe your campaign and our AI will find the perfect matches
                </p>
              </div>

              {/* Search form */}
              <Card>
                <CardHeader>
                  <CardTitle>AI-Powered Search</CardTitle>
                </CardHeader>
                <form onSubmit={handleMatch} className="space-y-4">
                  <Textarea
                    label="Campaign Description"
                    placeholder="Describe your campaign, target audience, goals, and the type of creator you're looking for..."
                    rows={4}
                    value={matchForm.business_description}
                    onChange={(e) =>
                      setMatchForm({ ...matchForm, business_description: e.target.value })
                    }
                    required
                  />
                  <div className="grid md:grid-cols-2 gap-4">
                    <Input
                      label="Budget Minimum ($)"
                      type="number"
                      placeholder="1000"
                      icon={<DollarSign className="h-4 w-4" />}
                      value={matchForm.budget_min}
                      onChange={(e) =>
                        setMatchForm({ ...matchForm, budget_min: e.target.value })
                      }
                      required
                    />
                    <Input
                      label="Budget Maximum ($)"
                      type="number"
                      placeholder="5000"
                      icon={<DollarSign className="h-4 w-4" />}
                      value={matchForm.budget_max}
                      onChange={(e) =>
                        setMatchForm({ ...matchForm, budget_max: e.target.value })
                      }
                      required
                    />
                  </div>

                  <div className="rounded-lg border border-surface-300 bg-surface-50/50 p-4 space-y-3">
                    <div className="flex items-start gap-2">
                      <MapPin className="h-4 w-4 text-brand-400 mt-0.5 shrink-0" />
                      <div>
                        <p className="text-sm font-medium text-zinc-200">
                          Target audience locations
                        </p>
                        <p className="text-xs text-zinc-500 mt-0.5">
                          Optional. We match these to each creator&apos;s audience geography (not your company address).
                        </p>
                      </div>
                    </div>
                    <div>
                      <p className="text-xs text-zinc-500 mb-2">Countries</p>
                      <div className="flex flex-wrap gap-3">
                        {TARGET_AUDIENCE_COUNTRIES.map((c) => (
                          <label
                            key={c}
                            className="flex items-center gap-2 text-sm text-zinc-300 cursor-pointer"
                          >
                            <input
                              type="checkbox"
                              className="rounded border-surface-400 text-brand-500 focus:ring-brand-500"
                              checked={matchForm.audience_countries.includes(c)}
                              onChange={(e) =>
                                setMatchForm({
                                  ...matchForm,
                                  audience_countries: toggleAudienceItem(
                                    matchForm.audience_countries,
                                    c,
                                    e.target.checked
                                  ),
                                })
                              }
                            />
                            {c}
                          </label>
                        ))}
                      </div>
                    </div>
                    <div>
                      <p className="text-xs text-zinc-500 mb-2">Cities</p>
                      <div className="flex flex-wrap gap-x-4 gap-y-2">
                        {TARGET_AUDIENCE_CITIES.map((c) => (
                          <label
                            key={c}
                            className="flex items-center gap-2 text-sm text-zinc-300 cursor-pointer"
                          >
                            <input
                              type="checkbox"
                              className="rounded border-surface-400 text-brand-500 focus:ring-brand-500"
                              checked={matchForm.audience_cities.includes(c)}
                              onChange={(e) =>
                                setMatchForm({
                                  ...matchForm,
                                  audience_cities: toggleAudienceItem(
                                    matchForm.audience_cities,
                                    c,
                                    e.target.checked
                                  ),
                                })
                              }
                            />
                            {c}
                          </label>
                        ))}
                      </div>
                    </div>
                  </div>

                  <Button
                    type="submit"
                    loading={matching}
                    icon={<Search className="h-4 w-4" />}
                  >
                    {matching ? 'Analyzing...' : 'Find Matching Creators'}
                  </Button>
                </form>
              </Card>

              {/* Match results */}
              {matchResults && (
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <h2 className="text-lg font-semibold text-zinc-100">
                      {matchResults.matches.length} Creators Found
                    </h2>
                    {matchResults.business_requirements.top_niche && (
                      <Badge variant="purple">
                        <Target className="h-3 w-3 mr-1" />
                        Best niche: {matchResults.business_requirements.top_niche}
                      </Badge>
                    )}
                  </div>

                  <div className="grid gap-4">
                    {matchResults.matches.map((match) => (
                      <InfluencerMatchCard
                        key={match.profile.id}
                        match={match}
                        onRequestCollab={() => {
                          setCollabModal(match);
                          setCollabForm({
                            message: '',
                            campaign_description: matchForm.business_description,
                            budget_offer: matchForm.budget_max,
                          });
                        }}
                        hasPending={collabs.some(
                          (c) =>
                            c.influencer === match.profile.id &&
                            c.status === 'PENDING',
                        )}
                      />
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* COLLABORATIONS TAB */}
          {activeTab === 'collaborations' && (
            <div className="space-y-6">
              <div>
                <h1 className="text-2xl font-bold text-zinc-100">
                  Collaborations
                </h1>
                <p className="text-sm text-zinc-500 mt-1">
                  Track your collaboration requests
                </p>
              </div>

              {collabs.length === 0 ? (
                <Card>
                  <EmptyState
                    icon={<Handshake className="h-8 w-8" />}
                    title="No Collaborations Yet"
                    description="Find creators and send collaboration requests to get started."
                  />
                </Card>
              ) : (
                <div className="space-y-4">
                  {collabs.map((c) => (
                    <Card key={c.id} hover className="!p-0">
                      <div className="p-5">
                        <div className="flex items-start justify-between mb-3">
                          <div>
                            <div className="flex items-center gap-2 mb-1">
                              <h3 className="font-semibold text-zinc-100">
                                {c.influencer_display?.display_name ??
                                  c.influencer_display?.instagram_handle ??
                                  `Creator #${c.influencer}`}
                              </h3>
                              <Badge
                                variant={
                                  c.status === 'ACCEPTED'
                                    ? 'success'
                                    : c.status === 'REJECTED'
                                      ? 'danger'
                                      : 'warning'
                                }
                              >
                                {c.status === 'PENDING' && <Clock className="h-3 w-3 mr-1" />}
                                {c.status === 'ACCEPTED' && <CheckCircle2 className="h-3 w-3 mr-1" />}
                                {c.status === 'REJECTED' && <XCircle className="h-3 w-3 mr-1" />}
                                {c.status}
                              </Badge>
                            </div>
                            {c.budget_offer && (
                              <p className="text-sm text-zinc-500">
                                Budget: ${Number(c.budget_offer).toLocaleString()}
                              </p>
                            )}
                          </div>
                          <span className="text-xs text-zinc-600">
                            {new Date(c.created_at).toLocaleDateString()}
                          </span>
                        </div>

                        {c.message && (
                          <p className="text-sm text-zinc-400 mb-2">
                            {c.message}
                          </p>
                        )}

                        {/* Reveal full profile on acceptance */}
                        {c.status === 'ACCEPTED' && c.influencer_display?.instagram_handle && (
                          <div className="mt-3 p-4 rounded-lg bg-emerald-50 border border-emerald-200">
                            <p className="text-xs text-emerald-400 font-medium mb-2">
                              Creator identity revealed
                            </p>
                            <p className="text-sm text-zinc-200">
                              <span className="font-semibold">
                                @{c.influencer_display.instagram_handle}
                              </span>
                              {' — '}
                              {c.influencer_display.user && typeof c.influencer_display.user === 'object' && 'first_name' in c.influencer_display.user
                                ? `${c.influencer_display.user.first_name} ${c.influencer_display.user.last_name}`
                                : ''}
                            </p>
                          </div>
                        )}

                        {c.response_message && (
                          <div className="mt-3 p-3 rounded-lg bg-surface-50 border border-surface-300">
                            <p className="text-xs text-zinc-500 mb-1">Creator's response</p>
                            <p className="text-sm text-zinc-300">{c.response_message}</p>
                          </div>
                        )}
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* SEARCH HISTORY TAB */}
          {activeTab === 'history' && (
            <div className="space-y-6">
              <div>
                <h1 className="text-2xl font-bold text-zinc-100">
                  Search History
                </h1>
                <p className="text-sm text-zinc-500 mt-1">
                  Your past creator searches
                </p>
              </div>

              {history.length === 0 ? (
                <Card>
                  <EmptyState
                    icon={<History className="h-8 w-8" />}
                    title="No Searches Yet"
                    description="Your past searches will appear here once you start finding creators."
                  />
                </Card>
              ) : (
                <div className="space-y-3">
                  {history.map((s) => (
                    <Card key={s.id} hover>
                      <div className="flex items-start justify-between">
                        <div className="flex-1 min-w-0 mr-4">
                          <p className="text-sm text-zinc-200 line-clamp-2 mb-2">
                            {s.business_description}
                          </p>
                          <div className="flex items-center gap-4 text-xs text-zinc-500">
                            <span className="flex items-center gap-1">
                              <DollarSign className="h-3 w-3" />
                              ${s.budget_min} — ${s.budget_max}
                            </span>
                            <span className="flex items-center gap-1">
                              <Users className="h-3 w-3" />
                              {s.matches_count} matches
                            </span>
                          </div>
                          {(s.audience_countries?.length || s.audience_cities?.length) ? (
                            <p className="text-xs text-zinc-600 mt-2 flex items-center gap-1">
                              <MapPin className="h-3 w-3 shrink-0" />
                              <span>
                                Audience:
                                {[...(s.audience_countries ?? []), ...(s.audience_cities ?? [])].join(', ')}
                              </span>
                            </p>
                          ) : null}
                        </div>
                        <span className="text-xs text-zinc-600 whitespace-nowrap">
                          {new Date(s.created_at).toLocaleDateString()}
                        </span>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* PROFILE TAB — account email / name / password (separate from company profile on Overview) */}
          {activeTab === 'profile' && (
            <AccountSettingsPanel onToast={showToast} />
          )}

          {/* Send collab modal */}
          <Modal
            open={!!collabModal}
            onClose={() => setCollabModal(null)}
            title="Send Collaboration Request"
          >
            {collabModal && (
              <div className="space-y-4">
                <div className="p-4 rounded-lg bg-surface-50 border border-surface-300">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium text-zinc-200">
                      {collabModal.profile.display_name}
                    </span>
                    <Badge variant="purple">
                      {(collabModal.match_score * 100).toFixed(0)}% match
                    </Badge>
                  </div>
                  <div className="grid grid-cols-3 gap-3 text-xs text-zinc-500">
                    <div>
                      <p className="text-zinc-400 font-medium">Followers</p>
                      <p>{formatNumber(collabModal.profile.followers_count)}</p>
                    </div>
                    <div>
                      <p className="text-zinc-400 font-medium">Engagement</p>
                      <p>{collabModal.profile.engagement_rate_percent?.toFixed(2)}%</p>
                    </div>
                    <div>
                      <p className="text-zinc-400 font-medium">Niche</p>
                      <p>{collabModal.profile.ai_predicted_niche}</p>
                    </div>
                  </div>
                </div>

                <Textarea
                  label="Message to Creator"
                  placeholder="Introduce your brand and explain why this would be a great collaboration..."
                  rows={3}
                  value={collabForm.message}
                  onChange={(e) =>
                    setCollabForm({ ...collabForm, message: e.target.value })
                  }
                />
                <Textarea
                  label="Campaign Description"
                  placeholder="Describe the campaign, deliverables, and timeline..."
                  rows={3}
                  value={collabForm.campaign_description}
                  onChange={(e) =>
                    setCollabForm({ ...collabForm, campaign_description: e.target.value })
                  }
                />
                <Input
                  label="Budget Offer ($)"
                  type="number"
                  placeholder="3000"
                  icon={<DollarSign className="h-4 w-4" />}
                  value={collabForm.budget_offer}
                  onChange={(e) =>
                    setCollabForm({ ...collabForm, budget_offer: e.target.value })
                  }
                />

                <Button
                  className="w-full"
                  loading={sendingCollab}
                  onClick={handleSendCollab}
                  icon={<Send className="h-4 w-4" />}
                >
                  Send Request
                </Button>
              </div>
            )}
          </Modal>
        </>
      )}
    </DashboardLayout>
  );
}

/* ---------- Influencer Match Card ---------- */

function InfluencerMatchCard({
  match,
  onRequestCollab,
  hasPending,
}: {
  match: InfluencerMatch;
  onRequestCollab: () => void;
  hasPending: boolean;
}) {
  const p = match.profile;
  return (
    <Card hover className="!p-0">
      <div className="p-5">
        <div className="flex items-start justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="h-12 w-12 rounded-xl bg-brand-50 flex items-center justify-center text-brand-600 font-bold">
              {p.display_name?.[0] ?? '#'}
            </div>
            <div>
              <h3 className="font-semibold text-zinc-100">{p.display_name}</h3>
              <div className="flex items-center gap-2 mt-0.5">
                {p.ai_predicted_niche && (
                  <Badge variant="purple">{p.ai_predicted_niche}</Badge>
                )}
                {p.verification_status && (
                  <Badge variant="success">Connected</Badge>
                )}
              </div>
            </div>
          </div>
          <div className="text-right">
            <div className="text-2xl font-bold text-brand-600">
              {(match.match_score * 100).toFixed(0)}%
            </div>
            <p className="text-xs text-zinc-500">Match Score</p>
          </div>
        </div>

        {/* Stats grid */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
          <MiniStat
            icon={<Users className="h-3.5 w-3.5" />}
            label="Followers"
            value={formatNumber(p.followers_count)}
          />
          <MiniStat
            icon={<Activity className="h-3.5 w-3.5" />}
            label="Engagement"
            value={`${p.engagement_rate_percent?.toFixed(2) ?? 0}%`}
          />
          <MiniStat
            icon={<Eye className="h-3.5 w-3.5" />}
            label="Avg Reach"
            value={formatNumber(p.ave_reach)}
          />
          <MiniStat
            icon={<BarChart3 className="h-3.5 w-3.5" />}
            label="Avg Impressions"
            value={formatNumber(p.ave_impressions)}
          />
        </div>

        {/* Pricing + scores */}
        <div className="flex items-center justify-between p-3 rounded-lg bg-surface-50 border border-surface-300 mb-4">
          <div className="flex items-center gap-4 text-xs">
            <span className="text-zinc-500">
              <span className="text-zinc-300 font-medium">Est. Price: </span>
              {p.estimated_price_min && p.estimated_price_max
                ? `$${formatNumber(p.estimated_price_min)} — $${formatNumber(p.estimated_price_max)}`
                : 'N/A'}
            </span>
            <span className="text-zinc-500">
              Niche: <span className="text-brand-400">{(match.niche_similarity * 100).toFixed(0)}%</span>
            </span>
            <span className="text-zinc-500">
              Budget Fit: <span className="text-emerald-400">{(match.budget_fit * 100).toFixed(0)}%</span>
            </span>
            {match.location_match_score != null && (
              <span className="text-zinc-500">
                Audience geo:{' '}
                <span className="text-sky-400">
                  {(match.location_match_score * 100).toFixed(0)}%
                </span>
              </span>
            )}
          </div>
          {match.price_info?.is_affordable === false && (
            <Badge variant="warning">Above budget</Badge>
          )}
        </div>

        {/* Audience */}
        <div className="flex items-center gap-3 text-xs text-zinc-500 mb-4">
          <span>
            <MessageSquare className="inline h-3 w-3 mr-1" />
            {p.audience_summary_string || `${p.female_audience_percentage?.toFixed(0) ?? '?'}% F / ${p.male_audience_percentage?.toFixed(0) ?? '?'}% M`}
          </span>
        </div>

        <Button
          size="sm"
          onClick={onRequestCollab}
          disabled={hasPending}
          icon={hasPending ? <Clock className="h-4 w-4" /> : <Send className="h-4 w-4" />}
        >
          {hasPending ? 'Request Pending' : 'Request Collaboration'}
        </Button>
      </div>
    </Card>
  );
}

function MiniStat({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
}) {
  return (
    <div className="p-2.5 rounded-lg bg-surface-50">
      <div className="flex items-center gap-1 text-zinc-500 mb-1">
        {icon}
        <span className="text-[11px]">{label}</span>
      </div>
      <p className="text-sm font-semibold text-zinc-200">{value}</p>
    </div>
  );
}
