import { useEffect, useState, useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
  Users,
  Eye,
  TrendingUp,
  Activity,
  RefreshCw,
  Link2,
  CheckCircle2,
  XCircle,
  Clock,
  Camera,
  Handshake,
  Image,
  BarChart3,
  DollarSign,
  MessageSquare,
} 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 { EmptyState } from '../../components/ui/EmptyState';
import { Loading } from '../../components/ui/Loading';
import { Modal } from '../../components/ui/Modal';
import { Textarea } from '../../components/ui/Input';
import { EngagementChart } from '../../components/charts/EngagementChart';
import { AudienceChart } from '../../components/charts/AudienceChart';
import { AccountSettingsPanel } from '../../components/profile/AccountSettingsPanel';
import { influencerService } from '../../services/influencer';
import { collaborationService } from '../../services/collaboration';
import { handleApiError } from '../../services/api';
import type { InfluencerProfile, MediaPost } from '../../types/influencer';
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();
}

/**
 * Tooltip copy for overview stat cards and analytics sections.
 * Time windows align with backend Instagram sync (see influencers/services/data_service.py):
 * — Account insights (e.g. growth context): daily series Meta returns (~last 30 days typical).
 * — Post metrics: averaged over up to 100 most recent posts; each value is usually lifetime for that post.
 * — Follower demographics: current follower breakdown (Meta lifetime-style). Reached-age fallback: this month.
 */
const DASHBOARD_HELP = {
  followers:
    'Total followers on your account as of the last data sync (a point-in-time snapshot, not a 30-day total). The % trend next to it uses Instagram’s daily follower history: we compare the first and last day Meta returns, which is usually about the last 30 days (exact length depends on Meta’s API).',
  engagementRate:
    'Engagement rate = average interactions per post ÷ your current follower count × 100. Averages are built from up to 100 of your most recent synced posts. Each post’s interaction counts are typically lifetime for that post (from publish onward), not a fixed 30- or 50-day window. Higher % means more engagement relative to audience size.',
  avgReach:
    'Mean reach across your synced posts (up to 100 most recent). Instagram usually reports reach per post for that post’s lifetime (cumulative since it was published), then we average those values—not a rolling “last 30 days only” account total.',
  avgImpressions:
    'Mean impressions across your synced posts (up to 100 most recent). Impressions are total views of the post (repeat views count). Like reach, each post’s number is normally lifetime for that post, then averaged.',
  mediaPosts:
    'Total posts Instagram reports on your account at sync. Charts and averages use insights for up to 100 of your newest posts (backend limit), not every post if you have more.',
  avgEngagement:
    'Mean total interactions per post (likes, comments, saves, shares, etc. as Meta defines “engagement”) across up to 100 recent synced posts. Usually lifetime totals per post, then averaged.',
  avgSaves:
    'Mean saves per post across up to 100 recent synced posts—typically lifetime saves per post from Instagram, then averaged.',
  estPrice:
    'Estimated sponsorship range from our model using your latest synced profile and engagement signals (same post/average rules as above). Not a guarantee. Refresh data to update; not tied to a single 30-day window.',
  contentPerformance:
    'Chart uses your synced posts (up to 100) and their stored metrics. Each point reflects that post’s metrics (generally lifetime for that post) and its publish date on the timeline—not a uniform “last 30 days” slice for every series.',
  audienceDemographics:
    'Follower gender, age, and location breakdowns reflect your current follower audience as Meta reports it (lifetime-style composition). If you see age from “reached” data only, that piece uses Meta’s this-month reached-audience window. Missing slices mean Meta did not return data for your account.',
  nicheAnalysis:
    'Niche scores are computed from your synced posts and profile text at processing time (up to 100 recent posts), not a fixed 30- or 50-day rolling window. Percentages show model confidence per category.',
  authenticity:
    'Score is based on signals available at last processing (synced posts and profile). It is not limited to a specific day count; refresh data to re-run.',
  pendingRequests:
    'Brands that sent you a collaboration request. Review each offer to accept or decline. Listing shows current requests, not a historical 30-day filter.',
} as const;

export default function InfluencerDashboard() {
  const [searchParams] = useSearchParams();
  const [profile, setProfile] = useState<InfluencerProfile | null>(null);
  const [posts, setPosts] = useState<MediaPost[]>([]);
  const [collabs, setCollabs] = useState<CollaborationRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [connectingIg, setConnectingIg] = useState(false);
  const [respondModal, setRespondModal] = useState<CollaborationRequest | null>(null);
  const [responseMsg, setResponseMsg] = useState('');
  const [respondLoading, setRespondLoading] = useState(false);
  const [toast, setToast] = useState('');

  const igStatus = searchParams.get('instagram');

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [p, c] = await Promise.allSettled([
        influencerService.getProfile(),
        collaborationService.getInfluencerCollaborations(),
      ]);

      if (p.status === 'fulfilled') {
        setProfile(p.value);
        try {
          const m = await influencerService.getMediaPosts(p.value.id);
          setPosts(m);
        } catch { /* no posts yet */ }
      }
      if (c.status === 'fulfilled') setCollabs(c.value);
    } catch { /* handled per-call */ } finally {
      setLoading(false);
    }
  }, []);

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

  useEffect(() => {
    if (igStatus === 'success') setToast('Instagram connected successfully!');
    if (igStatus === 'error') setToast('Failed to connect Instagram. Please try again.');
  }, [igStatus]);

  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(''), 5000);
    return () => clearTimeout(t);
  }, [toast]);

  const handleConnect = async () => {
    setConnectingIg(true);
    try {
      const url = await influencerService.getInstagramConnectUrl();
      window.location.href = url;
    } catch (err) {
      setToast(handleApiError(err));
      setConnectingIg(false);
    }
  };

  const handleRefresh = async () => {
    if (!profile) return;
    setRefreshing(true);
    try {
      await influencerService.refreshData(profile.id);
      setToast('Data refresh started. This may take a moment.');
      setTimeout(loadData, 3000);
    } catch (err) {
      setToast(handleApiError(err));
    } finally {
      setRefreshing(false);
    }
  };

  const handleRespond = async (status: 'ACCEPTED' | 'REJECTED') => {
    if (!respondModal) return;
    setRespondLoading(true);
    try {
      await collaborationService.respondToCollaboration(respondModal.id, {
        status,
        response_message: responseMsg,
      });
      setRespondModal(null);
      setResponseMsg('');
      setToast(status === 'ACCEPTED' ? 'Collaboration accepted!' : 'Collaboration declined.');
      const updated = await collaborationService.getInfluencerCollaborations();
      setCollabs(updated);
    } catch (err) {
      setToast(handleApiError(err));
    } finally {
      setRespondLoading(false);
    }
  };

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

  const pendingCollabs = collabs.filter((c) => c.status === 'PENDING');

  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 className="flex items-center justify-between">
                <div>
                  <h1 className="text-2xl font-bold text-zinc-100">Overview</h1>
                  <p className="text-sm text-zinc-500 mt-1">
                    Your Instagram performance at a glance
                  </p>
                </div>
                {profile && (
                  <Button
                    variant="secondary"
                    size="sm"
                    loading={refreshing}
                    onClick={handleRefresh}
                    icon={<RefreshCw className="h-4 w-4" />}
                  >
                    Refresh Data
                  </Button>
                )}
              </div>

              {!profile ? (
                <Card>
                  <EmptyState
                    icon={<Camera className="h-8 w-8" />}
                    title="Connect Your Instagram"
                    description="Link your Instagram Business account to unlock powerful analytics, get discovered by brands, and start earning."
                    action={
                      <Button
                        loading={connectingIg}
                        onClick={handleConnect}
                        icon={<Link2 className="h-4 w-4" />}
                      >
                        Connect Instagram
                      </Button>
                    }
                  />
                </Card>
              ) : (
                <>
                  {/* Profile banner */}
                  <Card className="!p-0 overflow-hidden">
                    <div className="h-16 bg-gray-50 border-b border-gray-100" />
                    <div className="px-6 pb-6 -mt-6">
                      <div className="flex items-end gap-4">
                        <div className="h-14 w-14 rounded-xl bg-brand-600 flex items-center justify-center text-white text-lg font-bold border-4 border-white">
                          {profile.instagram_handle?.[0]?.toUpperCase() ?? 'S'}
                        </div>
                        <div className="flex-1 pb-1">
                          <h2 className="text-lg font-semibold text-zinc-100">
                            @{profile.instagram_handle}
                          </h2>
                          <div className="flex items-center gap-3 mt-1">
                            {profile.ai_predicted_niche && (
                              <Badge variant="purple">{profile.ai_predicted_niche}</Badge>
                            )}
                            {profile.verification_status && (
                              <Badge variant="success">Connected</Badge>
                            )}
                            <Badge variant={
                              profile.data_processing_status === 'COMPLETED' ? 'success' :
                              profile.data_processing_status === 'PROCESSING' ? 'warning' : 'default'
                            }>
                              {profile.data_processing_status}
                            </Badge>
                          </div>
                        </div>
                      </div>
                    </div>
                  </Card>

                  {/* Metrics */}
                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <StatCard
                      label="Followers"
                      value={formatNumber(profile.followers_count)}
                      icon={<Users className="h-5 w-5" />}
                      trend={profile.follower_growth_rate_percent}
                      info={DASHBOARD_HELP.followers}
                    />
                    <StatCard
                      label="Engagement Rate"
                      value={`${profile.engagement_rate_percent?.toFixed(2) ?? 0}%`}
                      icon={<Activity className="h-5 w-5" />}
                      info={DASHBOARD_HELP.engagementRate}
                    />
                    <StatCard
                      label="Avg Reach"
                      value={formatNumber(profile.ave_reach)}
                      icon={<Eye className="h-5 w-5" />}
                      info={DASHBOARD_HELP.avgReach}
                    />
                    <StatCard
                      label="Avg Impressions"
                      value={formatNumber(profile.ave_impressions)}
                      icon={<TrendingUp className="h-5 w-5" />}
                      info={DASHBOARD_HELP.avgImpressions}
                    />
                  </div>

                  {/* Second row */}
                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <StatCard
                      label="Media Posts"
                      value={formatNumber(profile.media_count)}
                      icon={<Image className="h-5 w-5" />}
                      info={DASHBOARD_HELP.mediaPosts}
                    />
                    <StatCard
                      label="Avg Engagement"
                      value={formatNumber(profile.ave_engagement)}
                      icon={<BarChart3 className="h-5 w-5" />}
                      info={DASHBOARD_HELP.avgEngagement}
                    />
                    <StatCard
                      label="Avg Saves"
                      value={formatNumber(profile.ave_saves)}
                      icon={<BarChart3 className="h-5 w-5" />}
                      info={DASHBOARD_HELP.avgSaves}
                    />
                    <StatCard
                      label="Est. Price Range"
                      value={
                        profile.estimated_price_min && profile.estimated_price_max
                          ? `$${formatNumber(profile.estimated_price_min)} - $${formatNumber(profile.estimated_price_max)}`
                          : 'N/A'
                      }
                      icon={<DollarSign className="h-5 w-5" />}
                      info={DASHBOARD_HELP.estPrice}
                    />
                  </div>

                  {/* Pending collabs preview */}
                  {pendingCollabs.length > 0 && (
                    <Card>
                      <CardHeader>
                        <CardTitle info={DASHBOARD_HELP.pendingRequests}>
                          Pending Requests ({pendingCollabs.length})
                        </CardTitle>
                      </CardHeader>
                      <div className="space-y-3">
                        {pendingCollabs.slice(0, 3).map((c) => (
                          <div
                            key={c.id}
                            className="flex items-center justify-between p-4 rounded-lg bg-surface-50 border border-surface-300"
                          >
                            <div>
                              <p className="text-sm font-medium text-zinc-200">
                                {c.business_name}
                              </p>
                              <p className="text-xs text-zinc-500">
                                {c.business_industry} &middot;{' '}
                                {c.budget_offer ? `$${c.budget_offer}` : 'No budget specified'}
                              </p>
                            </div>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setRespondModal(c)}
                            >
                              Review
                            </Button>
                          </div>
                        ))}
                      </div>
                    </Card>
                  )}
                </>
              )}
            </div>
          )}

          {/* ANALYTICS TAB */}
          {activeTab === 'analytics' && (
            <div className="space-y-6">
              <div>
                <h1 className="text-2xl font-bold text-zinc-100">Analytics</h1>
                <p className="text-sm text-zinc-500 mt-1">
                  Deep dive into your content performance
                </p>
              </div>

              {!profile ? (
                <Card>
                  <EmptyState
                    icon={<BarChart3 className="h-8 w-8" />}
                    title="No Data Yet"
                    description="Connect your Instagram account to see detailed analytics."
                  />
                </Card>
              ) : (
                <>
                  {/* Engagement over time */}
                  <Card>
                    <CardHeader>
                      <CardTitle info={DASHBOARD_HELP.contentPerformance}>
                        Content Performance
                      </CardTitle>
                      <Badge variant="purple">{posts.length} posts</Badge>
                    </CardHeader>
                    {posts.length > 0 ? (
                      <EngagementChart posts={posts} />
                    ) : (
                      <p className="text-sm text-zinc-500 py-8 text-center">
                        No posts data available yet. Data will appear after processing completes.
                      </p>
                    )}
                  </Card>

                  <div className="grid md:grid-cols-2 gap-6">
                    {/* Audience */}
                    <Card>
                      <CardHeader>
                        <CardTitle info={DASHBOARD_HELP.audienceDemographics}>
                          Audience Demographics
                        </CardTitle>
                      </CardHeader>
                      <AudienceChart
                        female={profile.female_audience_percentage}
                        male={profile.male_audience_percentage}
                        ageDistribution={profile.audience_age_distribution}
                        topCountries={profile.audience_top_countries}
                        topCities={profile.audience_top_cities}
                      />
                      {profile.audience_summary_string && (
                        <p className="text-xs text-zinc-500 mt-2 text-center">
                          {profile.audience_summary_string}
                        </p>
                      )}
                    </Card>

                    {/* Niche breakdown */}
                    <Card>
                      <CardHeader>
                        <CardTitle info={DASHBOARD_HELP.nicheAnalysis}>
                          Niche Analysis
                        </CardTitle>
                      </CardHeader>
                      {profile.niche_probabilities &&
                      Object.keys(profile.niche_probabilities).length > 0 ? (
                        <div className="space-y-3">
                          {Object.entries(profile.niche_probabilities)
                            .sort(([, a], [, b]) => b - a)
                            .slice(0, 6)
                            .map(([niche, prob]) => (
                              <div key={niche}>
                                <div className="flex items-center justify-between text-sm mb-1">
                                  <span className="text-zinc-300">{niche}</span>
                                  <span className="text-zinc-500">
                                    {(prob * 100).toFixed(1)}%
                                  </span>
                                </div>
                                    <div className="h-1.5 rounded-full bg-gray-100 overflow-hidden">
                                  <div
                                    className="h-full rounded-full bg-brand-500"
                                    style={{ width: `${prob * 100}%` }}
                                  />
                                </div>
                              </div>
                            ))}
                        </div>
                      ) : (
                        <p className="text-sm text-zinc-500 py-4 text-center">
                          Processing niche data...
                        </p>
                      )}
                      {profile.niche_classification_explanation && (
                        <p className="text-xs text-zinc-500 mt-4 p-3 bg-surface-50 rounded-lg">
                          {profile.niche_classification_explanation}
                        </p>
                      )}
                    </Card>
                  </div>

                  {/* Authenticity */}
                  {profile.authenticity_score && (
                    <Card>
                      <CardHeader>
                        <CardTitle info={DASHBOARD_HELP.authenticity}>
                          Authenticity Score
                        </CardTitle>
                      </CardHeader>
                      <div className="flex items-center gap-4">
                        <div className="text-3xl font-bold text-emerald-400">
                          {profile.authenticity_score}
                        </div>
                        {profile.bot_detection_flags && profile.bot_detection_flags.length > 0 && (
                          <div className="flex flex-wrap gap-2">
                            {profile.bot_detection_flags.map((flag, i) => (
                              <Badge key={i} variant="warning">{flag}</Badge>
                            ))}
                          </div>
                        )}
                      </div>
                    </Card>
                  )}
                </>
              )}
            </div>
          )}

          {/* PROFILE TAB */}
          {activeTab === 'profile' && (
            <AccountSettingsPanel onToast={(msg) => setToast(msg)} />
          )}

          {/* 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">
                  Manage collaboration requests from brands
                </p>
              </div>

              {collabs.length === 0 ? (
                <Card>
                  <EmptyState
                    icon={<Handshake className="h-8 w-8" />}
                    title="No Collaboration Requests"
                    description="When brands want to work with you, their requests will appear here. Make sure your profile is complete to get discovered."
                  />
                </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.business_name}
                              </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>
                            <p className="text-sm text-zinc-500">
                              {c.business_industry}
                              {c.budget_offer && ` · Budget: $${Number(c.budget_offer).toLocaleString()}`}
                            </p>
                          </div>
                          {c.status === 'PENDING' && (
                            <Button
                              size="sm"
                              onClick={() => setRespondModal(c)}
                            >
                              Respond
                            </Button>
                          )}
                        </div>
                        {c.message && (
                          <div className="p-3 rounded-lg bg-surface-50 border border-surface-300 mb-3">
                            <p className="text-xs text-zinc-500 mb-1 flex items-center gap-1">
                              <MessageSquare className="h-3 w-3" /> Message
                            </p>
                            <p className="text-sm text-zinc-300">{c.message}</p>
                          </div>
                        )}
                        {c.campaign_description && (
                          <p className="text-sm text-zinc-400">
                            <span className="font-medium text-zinc-300">Campaign: </span>
                            {c.campaign_description}
                          </p>
                        )}
                        {c.response_message && (
                          <div className="mt-3 p-3 rounded-lg bg-brand-50 border border-brand-100">
                            <p className="text-xs text-zinc-500 mb-1">Your response</p>
                            <p className="text-sm text-zinc-300">{c.response_message}</p>
                          </div>
                        )}
                        <p className="text-xs text-zinc-600 mt-3">
                          {new Date(c.created_at).toLocaleDateString('en-US', {
                            month: 'long',
                            day: 'numeric',
                            year: 'numeric',
                          })}
                        </p>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Respond Modal */}
          <Modal
            open={!!respondModal}
            onClose={() => {
              setRespondModal(null);
              setResponseMsg('');
            }}
            title="Collaboration Request"
          >
            {respondModal && (
              <div className="space-y-4">
                <div>
                  <p className="text-sm text-zinc-400 mb-1">From</p>
                  <p className="text-zinc-100 font-medium">
                    {respondModal.business_name}
                  </p>
                  <p className="text-sm text-zinc-500">
                    {respondModal.business_industry}
                  </p>
                </div>
                {respondModal.budget_offer && (
                  <div>
                    <p className="text-sm text-zinc-400 mb-1">Budget Offer</p>
                    <p className="text-lg font-semibold text-emerald-400">
                      ${Number(respondModal.budget_offer).toLocaleString()}
                    </p>
                  </div>
                )}
                {respondModal.message && (
                  <div>
                    <p className="text-sm text-zinc-400 mb-1">Message</p>
                    <p className="text-sm text-zinc-300">
                      {respondModal.message}
                    </p>
                  </div>
                )}
                {respondModal.campaign_description && (
                  <div>
                    <p className="text-sm text-zinc-400 mb-1">Campaign</p>
                    <p className="text-sm text-zinc-300">
                      {respondModal.campaign_description}
                    </p>
                  </div>
                )}

                <Textarea
                  label="Your Response (optional)"
                  placeholder="Write a message to the brand..."
                  rows={3}
                  value={responseMsg}
                  onChange={(e) => setResponseMsg(e.target.value)}
                />

                <div className="flex gap-3 pt-2">
                  <Button
                    className="flex-1"
                    loading={respondLoading}
                    onClick={() => handleRespond('ACCEPTED')}
                    icon={<CheckCircle2 className="h-4 w-4" />}
                  >
                    Accept
                  </Button>
                  <Button
                    className="flex-1"
                    variant="danger"
                    loading={respondLoading}
                    onClick={() => handleRespond('REJECTED')}
                    icon={<XCircle className="h-4 w-4" />}
                  >
                    Decline
                  </Button>
                </div>
              </div>
            )}
          </Modal>
        </>
      )}
    </DashboardLayout>
  );
}
