'use client';

import { useAuth } from '@/lib/hooks/useAuth';
import { useRealtimeContext } from '@/components/realtime/RealtimeProvider';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import {
  Users, MessageSquare, TrendingUp, DollarSign, Target, UserPlus,
  Mail, CheckCircle2, Circle, Zap, Building2, ArrowUpRight, Clock,
  Rocket, Activity, Sparkles, Settings, BarChart3, Wifi, WifiOff,
  AlertCircle, PhoneCall, Megaphone, UserCheck
} from 'lucide-react';

interface DashboardStats {
  totalContacts: number;
  activeConversations: number;
  openOpportunities: number;
  pipelineValue: number;
}

export default function DashboardPage() {
  const { user } = useAuth();
  const { isConnected } = useRealtimeContext();
  const [stats, setStats] = useState<DashboardStats>({
    totalContacts: 0,
    activeConversations: 0,
    openOpportunities: 0,
    pipelineValue: 0,
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchStats() {
      try {
        const response = await fetch('/api/v1/dashboard/stats');
        if (response.ok) {
          const data = await response.json();
          setStats(data);
        }
      } catch (error) {
        console.error('Failed to fetch stats:', error);
      } finally {
        setLoading(false);
      }
    }
    fetchStats();
  }, []);

  const quickActions = [
    { name: 'Add Contact', href: '/contacts', icon: UserPlus, description: 'Import or create new contacts' },
    { name: 'Send Message', href: '/conversations', icon: Mail, description: 'Start a conversation' },
    { name: 'View Pipeline', href: '/opportunities', icon: Target, description: 'Track your deals' },
    { name: 'Get Leads', href: '/leads', icon: TrendingUp, description: 'Find new opportunities' },
  ];

  return (
    <div className="space-y-12 pb-8">
      {/* Header Section - Level 1 (subtle) since it's a page header, not main content */}
      <div className="clay-card-subtle p-6 border border-border/50">
        <div className="flex items-center justify-between flex-wrap gap-4">
          <div>
            <h1 className="text-3xl lg:text-4xl font-bold text-foreground mb-2">
              Welcome back{user?.firstName && <span className="text-primary">, {user.firstName}</span>}
            </h1>
            <p className="text-slate-500 text-lg">Here&apos;s what&apos;s happening with your portfolio today</p>
          </div>
          <div className={`flex items-center gap-2 px-4 py-2 rounded-full border transition-all ${
            isConnected
              ? 'bg-emerald-50 border-emerald-200'
              : 'bg-amber-50 border-amber-200'
          }`}>
            {isConnected ? (
              <>
                <Wifi className="w-4 h-4 text-emerald-600" />
                <span className="w-2 h-2 bg-emerald-500 rounded-full animate-pulse" />
                <span className="text-sm font-semibold text-emerald-700">Connected</span>
              </>
            ) : (
              <>
                <WifiOff className="w-4 h-4 text-amber-600" />
                <span className="w-2 h-2 bg-amber-500 rounded-full animate-pulse" />
                <span className="text-sm font-semibold text-amber-700">Connecting...</span>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Stats Grid */}
      <div>
        {/* Section header - Level 1 (subtle) */}
        <div className="clay-card-subtle p-5 border border-border/50 mb-6">
          <div className="flex items-center gap-3">
            <div className="w-11 h-11 rounded-xl bg-slate-100 flex items-center justify-center">
              <BarChart3 className="w-5 h-5 text-slate-600" />
            </div>
            <div>
              <h2 className="text-2xl font-bold text-foreground">Overview</h2>
              <p className="text-sm text-slate-500">Your key metrics at a glance</p>
            </div>
          </div>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-6">
          <StatCard
            title="Total Contacts"
            value={stats.totalContacts}
            icon={Users}
            loading={loading}
            trend={stats.totalContacts > 0 ? "+12%" : undefined}
            trendUp
            emptyMessage="No contacts yet"
            emptyAction={{ label: "Import contacts", href: "/contacts" }}
          />
          <StatCard
            title="Active Conversations"
            value={stats.activeConversations}
            icon={MessageSquare}
            loading={loading}
            trend={stats.activeConversations > 0 ? "+5%" : undefined}
            trendUp
            emptyMessage="No active chats"
            emptyAction={{ label: "Start a conversation", href: "/conversations" }}
          />
          <StatCard
            title="Open Opportunities"
            value={stats.openOpportunities}
            icon={Target}
            loading={loading}
            trend={stats.openOpportunities > 0 ? "+8%" : undefined}
            trendUp
            emptyMessage="No opportunities"
            emptyAction={{ label: "Create opportunity", href: "/opportunities" }}
          />
          <StatCard
            title="Pipeline Value"
            value={stats.pipelineValue}
            icon={DollarSign}
            loading={loading}
            trend={stats.pipelineValue > 0 ? "+23%" : undefined}
            trendUp
            highlight
            isCurrency
            emptyMessage="No pipeline value"
            emptyAction={{ label: "Add a deal", href: "/opportunities" }}
          />
        </div>
      </div>

      {/* Quick Actions */}
      <div>
        {/* Section header - Level 1 (subtle) */}
        <div className="clay-card-subtle p-5 border border-border/50 mb-6">
          <div className="flex items-center gap-3">
            <div className="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center">
              <Rocket className="w-5 h-5 text-primary" />
            </div>
            <div>
              <h2 className="text-2xl font-bold text-foreground">Quick Actions</h2>
              <p className="text-sm text-slate-500">Jump right into common tasks</p>
            </div>
          </div>
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-6">
          {quickActions.map((action) => {
            const Icon = action.icon;
            return (
              <Link key={action.name} href={action.href}>
                <div className="clay-card-interactive p-6 group border border-border/50 hover:border-primary/30 h-full">
                  <div className="flex items-start justify-between mb-4">
                    <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
                      <Icon className="w-6 h-6 text-primary" />
                    </div>
                    <ArrowUpRight className="w-5 h-5 text-muted-foreground opacity-0 group-hover:opacity-100 group-hover:text-primary transition-all" />
                  </div>
                  <h3 className="text-base font-bold text-foreground mb-2 group-hover:text-primary transition-colors">
                    {action.name}
                  </h3>
                  <p className="text-sm text-slate-500">{action.description}</p>
                </div>
              </Link>
            );
          })}
        </div>
      </div>

      {/* Bottom Section */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        <SetupProgress />
        <RecommendedTasks />
      </div>
    </div>
  );
}

function StatCard({
  title,
  value,
  icon: Icon,
  loading,
  trend,
  trendUp,
  highlight,
  isCurrency,
  emptyMessage,
  emptyAction
}: {
  title: string;
  value: string | number;
  icon: React.ComponentType<{ className?: string }>;
  loading: boolean;
  trend?: string;
  trendUp?: boolean;
  highlight?: boolean;
  isCurrency?: boolean;
  emptyMessage?: string;
  emptyAction?: { label: string; href: string };
}) {
  const numericValue = typeof value === 'number' ? value : parseFloat(value) || 0;
  const isEmpty = numericValue === 0;
  const displayValue = isCurrency ? `$${numericValue.toLocaleString()}` : value;

  return (
    <div className={`clay-card p-6 border border-border/50 ${
      highlight ? 'bg-gradient-to-br from-primary/5 to-primary/10 border-primary/20' : ''
    }`}>
      <div className="flex items-start justify-between mb-4">
        <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${
          highlight ? 'bg-primary/20' : 'bg-slate-100'
        }`}>
          <Icon className={`w-6 h-6 ${highlight ? 'text-primary' : 'text-slate-600'}`} />
        </div>
        {trend ? (
          <span className={`text-xs font-bold px-2.5 py-1 rounded-full ${
            trendUp
              ? 'bg-emerald-50 text-emerald-600 border border-emerald-200'
              : 'bg-red-50 text-red-600 border border-red-200'
          }`}>
            {trend}
          </span>
        ) : !loading && isEmpty ? (
          <span className="text-xs font-medium px-2.5 py-1 rounded-full bg-slate-100 text-slate-500 border border-slate-200">
            --
          </span>
        ) : null}
      </div>
      <div>
        {loading ? (
          <div className="h-9 w-24 bg-slate-100 rounded-lg animate-pulse" />
        ) : isEmpty ? (
          <div className="space-y-1.5">
            <p className={`text-3xl font-bold ${highlight ? 'text-primary/40' : 'text-muted-foreground/50'}`}>
              {isCurrency ? '$0' : '0'}
            </p>
            {emptyMessage && (
              <p className="text-sm text-slate-500">{emptyMessage}</p>
            )}
            {emptyAction && (
              <Link
                href={emptyAction.href}
                className="inline-flex items-center gap-1 text-sm font-medium text-primary hover:text-primary/80 transition-colors"
              >
                {emptyAction.label}
                <ArrowUpRight className="w-3.5 h-3.5" />
              </Link>
            )}
          </div>
        ) : (
          <p className={`text-3xl font-bold ${highlight ? 'text-primary' : 'text-foreground'}`}>
            {displayValue}
          </p>
        )}
        <p className="text-slate-500 font-medium mt-2 text-sm">{title}</p>
      </div>
    </div>
  );
}

function SetupProgress() {
  const [progress, setProgress] = useState({
    smsConfigured: false,
    emailConfigured: false,
    contactsImported: false,
    campaignsSetup: false,
  });

  useEffect(() => {
    fetch('/api/v1/onboarding/status')
      .then(res => res.json())
      .then(data => {
        if (data.setupStatus) {
          setProgress(data.setupStatus);
        }
      })
      .catch(() => {});
  }, []);

  const steps = [
    { key: 'smsConfigured', label: 'Configure SMS', description: 'Set up two-way texting', done: progress.smsConfigured, href: '/settings/sms', icon: MessageSquare },
    { key: 'emailConfigured', label: 'Set up Email', description: 'Connect your email account', done: progress.emailConfigured, href: '/settings/email', icon: Mail },
    { key: 'contactsImported', label: 'Import Contacts', description: 'Bring in your database', done: progress.contactsImported, href: '/contacts', icon: Users },
    { key: 'campaignsSetup', label: 'Create Campaigns', description: 'Automate your follow-ups', done: progress.campaignsSetup, href: '/campaigns', icon: Zap },
  ];

  const completedCount = steps.filter(s => s.done).length;
  const progressPercent = (completedCount / steps.length) * 100;
  const isComplete = progressPercent === 100;

  return (
    <div className="clay-card p-6 border border-border/50 h-full">
      {/* Header */}
      <div className="flex items-center justify-between mb-5 flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <div className={`w-11 h-11 rounded-xl flex items-center justify-center ${
            isComplete ? 'bg-emerald-100' : 'bg-primary/10'
          }`}>
            {isComplete ? (
              <CheckCircle2 className="w-5 h-5 text-emerald-600" />
            ) : (
              <Settings className="w-5 h-5 text-primary" />
            )}
          </div>
          <div>
            <h2 className="text-lg font-bold text-foreground">Setup Progress</h2>
            <p className="text-sm text-slate-500">
              {isComplete ? 'All set! You\'re ready to go' : 'Complete these steps to unlock all features'}
            </p>
          </div>
        </div>
        <div className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full font-bold text-sm ${
          isComplete
            ? 'bg-emerald-100 text-emerald-700'
            : 'bg-primary/10 text-primary'
        }`}>
          <span>{completedCount}</span>
          <span className="text-foreground/40 font-normal">/</span>
          <span>{steps.length}</span>
          <span className="font-medium ml-0.5">complete</span>
        </div>
      </div>

      {/* Progress Bar */}
      <div className="mb-5 p-3 rounded-lg bg-slate-50 border border-slate-200">
        <div className="flex justify-between items-center mb-2">
          <span className="text-xs font-medium text-foreground">
            {isComplete ? 'Setup Complete!' : `${completedCount} of ${steps.length} steps completed`}
          </span>
          <span className={`text-sm font-bold ${isComplete ? 'text-emerald-600' : 'text-primary'}`}>
            {Math.round(progressPercent)}%
          </span>
        </div>
        <div className="h-2.5 bg-slate-200 rounded-full overflow-hidden">
          <div
            className={`h-full rounded-full transition-all duration-700 ease-out ${
              isComplete
                ? 'bg-gradient-to-r from-emerald-500 to-emerald-400'
                : 'bg-gradient-to-r from-primary via-indigo-500 to-violet-500'
            }`}
            style={{ width: `${progressPercent}%` }}
          />
        </div>
      </div>

      {/* Steps List */}
      <div className="space-y-3">
        {steps.map((step, index) => {
          const StepIcon = step.icon;
          return (
            <div
              key={step.key}
              className={`flex items-center gap-3 p-3 rounded-lg transition-all ${
                step.done
                  ? 'bg-emerald-50 border border-emerald-200'
                  : 'bg-white border border-slate-200 hover:border-primary/30'
              }`}
            >
              {/* Step Number/Check */}
              <div className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${
                step.done
                  ? 'bg-emerald-500 text-white'
                  : 'bg-slate-100 text-slate-500 border border-slate-300'
              }`}>
                {step.done ? (
                  <CheckCircle2 className="w-4 h-4" />
                ) : (
                  <span className="font-bold text-xs">{index + 1}</span>
                )}
              </div>

              {/* Step Icon */}
              <div className={`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${
                step.done ? 'bg-emerald-100' : 'bg-slate-100'
              }`}>
                <StepIcon className={`w-4 h-4 ${step.done ? 'text-emerald-600' : 'text-slate-500'}`} />
              </div>

              {/* Step Content */}
              <div className="flex-1 min-w-0">
                <p className={`font-semibold text-sm ${step.done ? 'text-emerald-700' : 'text-foreground'}`}>
                  {step.label}
                </p>
                <p className="text-xs text-slate-500">{step.description}</p>
              </div>

              {/* Action Button */}
              {step.done ? (
                <span className="text-xs font-medium text-emerald-600 px-2 py-1 shrink-0">
                  Done
                </span>
              ) : (
                <Link
                  href={step.href}
                  className="px-3 py-1.5 text-xs font-semibold text-white bg-primary rounded-md hover:bg-primary/90 transition-colors shrink-0 flex items-center gap-1"
                >
                  Start
                  <ArrowUpRight className="w-3 h-3" />
                </Link>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

interface Recommendation {
  id: string;
  type: 'follow_up' | 'stale_lead' | 'pipeline_stuck' | 'campaign_response' | 'no_response';
  priority: 'high' | 'medium' | 'low';
  title: string;
  description: string;
  actionLabel: string;
  actionUrl: string;
  contactId?: string;
  contactName?: string;
  daysOverdue?: number;
  pipelineStage?: string;
}

function RecommendedTasks() {
  const [recommendations, setRecommendations] = useState<Recommendation[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchRecommendations() {
      try {
        const response = await fetch('/api/v1/dashboard/recommendations');
        if (response.ok) {
          const data = await response.json();
          setRecommendations(data.recommendations || []);
        } else {
          setError('Failed to load recommendations');
        }
      } catch (err) {
        console.error('Failed to fetch recommendations:', err);
        setError('Failed to load recommendations');
      } finally {
        setLoading(false);
      }
    }
    fetchRecommendations();
  }, []);

  const getIconForType = (type: Recommendation['type']) => {
    switch (type) {
      case 'follow_up':
        return UserCheck;
      case 'no_response':
        return PhoneCall;
      case 'pipeline_stuck':
        return Target;
      case 'campaign_response':
        return Megaphone;
      case 'stale_lead':
        return AlertCircle;
      default:
        return Zap;
    }
  };

  const getColorForPriority = (priority: Recommendation['priority']) => {
    switch (priority) {
      case 'high':
        return { bg: 'bg-red-100', icon: 'text-red-600', border: 'border-red-200 hover:border-red-300' };
      case 'medium':
        return { bg: 'bg-amber-100', icon: 'text-amber-600', border: 'border-amber-200 hover:border-amber-300' };
      case 'low':
        return { bg: 'bg-blue-100', icon: 'text-blue-600', border: 'border-blue-200 hover:border-blue-300' };
    }
  };

  return (
    <div className="clay-card p-6 border border-border/50 h-full flex flex-col">
      {/* Header */}
      <div className="flex items-center gap-3 mb-5">
        <div className="w-11 h-11 rounded-xl bg-gradient-to-br from-indigo-100 to-purple-100 flex items-center justify-center">
          <Zap className="w-5 h-5 text-indigo-600" />
        </div>
        <div>
          <h2 className="text-lg font-bold text-foreground">Recommended Tasks</h2>
          <p className="text-sm text-slate-500">AI-powered suggestions based on your CRM</p>
        </div>
      </div>

      {loading ? (
        <div className="space-y-3 flex-1">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="flex items-start gap-3 p-3 rounded-lg bg-slate-50 border border-slate-200">
              <div className="w-10 h-10 rounded-lg bg-slate-200 animate-pulse" />
              <div className="flex-1 space-y-2">
                <div className="h-4 w-3/4 bg-slate-200 rounded animate-pulse" />
                <div className="h-3 w-1/2 bg-slate-200 rounded animate-pulse" />
              </div>
              <div className="w-20 h-7 bg-slate-200 rounded animate-pulse" />
            </div>
          ))}
        </div>
      ) : error ? (
        <div className="text-center py-6 flex-1 flex flex-col justify-center">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-red-100 flex items-center justify-center">
            <AlertCircle className="w-8 h-8 text-red-500" />
          </div>
          <h3 className="text-base font-semibold text-foreground mb-2">
            Unable to load recommendations
          </h3>
          <p className="text-sm text-slate-500 mb-4">
            Make sure your MCP server is running
          </p>
          <button
            onClick={() => {
              setLoading(true);
              setError(null);
              fetch('/api/v1/dashboard/recommendations')
                .then(r => r.json())
                .then(data => setRecommendations(data.recommendations || []))
                .catch(() => setError('Failed to load recommendations'))
                .finally(() => setLoading(false));
            }}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-white bg-primary rounded-md hover:bg-primary/90 transition-colors mx-auto"
          >
            Try Again
          </button>
        </div>
      ) : recommendations.length > 0 ? (
        <div className="space-y-3 flex-1 overflow-y-auto">
          {recommendations.map((rec) => {
            const Icon = getIconForType(rec.type);
            const colors = getColorForPriority(rec.priority);
            return (
              <div
                key={rec.id}
                className={`flex items-start gap-3 p-3 rounded-lg bg-slate-50 border ${colors.border} transition-colors`}
              >
                <div className={`w-10 h-10 rounded-lg ${colors.bg} flex items-center justify-center shrink-0`}>
                  <Icon className={`w-5 h-5 ${colors.icon}`} />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-foreground text-sm font-medium">{rec.title}</p>
                  <p className="text-xs text-slate-500 mt-1">{rec.description}</p>
                </div>
                <Link
                  href={rec.actionUrl}
                  className="shrink-0 inline-flex items-center gap-1 px-2.5 py-1.5 text-xs font-medium text-primary bg-primary/10 rounded-md hover:bg-primary/20 transition-colors"
                >
                  {rec.actionLabel}
                  <ArrowUpRight className="w-3 h-3" />
                </Link>
              </div>
            );
          })}
        </div>
      ) : (
        /* Empty State - All caught up */
        <div className="text-center py-6 flex-1 flex flex-col justify-center">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-gradient-to-br from-green-100 to-emerald-100 flex items-center justify-center">
            <CheckCircle2 className="w-8 h-8 text-green-500" />
          </div>
          <h3 className="text-base font-semibold text-foreground mb-2">
            You're all caught up!
          </h3>
          <p className="text-sm text-slate-500 mb-5 max-w-xs mx-auto">
            No urgent tasks right now. Keep up the great work with your leads and deals.
          </p>
          <div className="flex flex-col sm:flex-row items-center justify-center gap-2">
            <Link
              href="/control-center"
              className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-white bg-primary rounded-md hover:bg-primary/90 transition-colors"
            >
              <Sparkles className="w-3.5 h-3.5" />
              Ask AI for Insights
            </Link>
            <Link
              href="/contacts"
              className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-primary bg-primary/10 rounded-md hover:bg-primary/20 transition-colors"
            >
              <UserPlus className="w-3.5 h-3.5" />
              Add More Contacts
            </Link>
          </div>
        </div>
      )}

      {/* Footer link to Control Center for more insights */}
      {recommendations.length > 0 && (
        <div className="border-t border-slate-200 pt-3 mt-3">
          <Link
            href="/control-center"
            className="text-xs text-primary hover:text-primary/80 font-medium flex items-center justify-center gap-1 transition-colors"
          >
            Get more insights with AI
            <Sparkles className="w-3 h-3" />
          </Link>
        </div>
      )}
    </div>
  );
}
