
'use client';

import { useEffect, useState } from 'react';
import { useSession } from 'next-auth/react';
import { motion } from 'framer-motion';
import { 
  Users, 
  Calculator, 
  FileText, 
  TrendingUp, 
  DollarSign,
  Clock,
  CheckCircle,
  AlertTriangle,
  Building2,
  Target,
  Activity,
  Award
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import Link from 'next/link';

interface DashboardStats {
  leads: {
    total: number;
    new: number;
    qualified: number;
    converted: number;
  };
  quotes: {
    total: number;
    sent: number;
    accepted: number;
    pending: number;
  };
  contracts: {
    total: number;
    active: number;
    completed: number;
    revenue: number;
  };
  partners: {
    total: number;
    active: number;
    topPerformer: string;
  };
}

const StatCard = ({ 
  title, 
  value, 
  change, 
  icon: Icon, 
  trend = 'up',
  description 
}: {
  title: string;
  value: string | number;
  change?: string;
  icon: any;
  trend?: 'up' | 'down' | 'neutral';
  description?: string;
}) => (
  <motion.div
    initial={{ opacity: 0, scale: 0.95 }}
    animate={{ opacity: 1, scale: 1 }}
    transition={{ duration: 0.3 }}
    className="card-hover"
  >
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">{title}</CardTitle>
        <Icon className="h-4 w-4 text-muted-foreground" />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        {change && (
          <div className="flex items-center space-x-1 text-xs text-muted-foreground">
            <span className={`flex items-center ${
              trend === 'up' ? 'text-green-600' : 
              trend === 'down' ? 'text-red-600' : 
              'text-gray-600'
            }`}>
              {trend === 'up' ? '↑' : trend === 'down' ? '↓' : '→'} {change}
            </span>
            <span>from last month</span>
          </div>
        )}
        {description && (
          <p className="text-xs text-muted-foreground mt-1">{description}</p>
        )}
      </CardContent>
    </Card>
  </motion.div>
);

export function DashboardContent() {
  const { data: session } = useSession() || {};
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [isLoading, setIsLoading] = useState(true);

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

    fetchStats();
  }, []);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="spinner w-8 h-8"></div>
      </div>
    );
  }

  const userRole = session?.user?.role;
  const userName = session?.user?.name?.split(' ')[0] || 'User';

  return (
    <div className="space-y-8">
      {/* Header */}
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
      >
        <div className="flex flex-col md:flex-row md:items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold gradient-text">
              Welcome back, to Quote2Contract!
            </h1>
            <p className="text-muted-foreground mt-1">
              Here's what's happening with your business today.
            </p>
          </div>
          <div className="flex items-center space-x-2 mt-4 md:mt-0">
            <Badge variant="outline" className="capitalize">
              {userRole?.toLowerCase()}
            </Badge>
            {session?.user?.companyName && (
              <Badge variant="secondary">
                {session.user.companyName}
              </Badge>
            )}
          </div>
        </div>
      </motion.div>

      {/* Quick Actions */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, delay: 0.1 }}
        className="grid grid-cols-1 md:grid-cols-4 gap-4"
      >
        {[
          { title: 'New Lead', href: '/leads/new', icon: Users, color: 'from-blue-500 to-blue-600' },
          { title: 'Create Quote', href: '/quotes/new', icon: Calculator, color: 'from-green-500 to-green-600' },
          { title: 'View Contracts', href: '/contracts', icon: FileText, color: 'from-purple-500 to-purple-600' },
          { title: 'Analytics', href: '/analytics', icon: TrendingUp, color: 'from-orange-500 to-orange-600' },
        ].map((action, index) => (
          <Link key={index} href={action.href}>
            <Card className="cursor-pointer card-hover">
              <CardContent className="p-4">
                <div className="flex items-center space-x-3">
                  <div className={`w-10 h-10 bg-gradient-to-r ${action.color} rounded-lg flex items-center justify-center`}>
                    <action.icon className="w-5 h-5 text-white" />
                  </div>
                  <span className="font-medium">{action.title}</span>
                </div>
              </CardContent>
            </Card>
          </Link>
        ))}
      </motion.div>

      {/* Stats Overview */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, delay: 0.2 }}
        className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6"
      >
        <StatCard
          title="Total Leads"
          value={stats?.leads?.total || 0}
          change="+12%"
          icon={Users}
          trend="up"
          description="Lead pipeline is healthy"
        />
        <StatCard
          title="Active Quotes"
          value={stats?.quotes?.pending || 0}
          change="+8%"
          icon={Calculator}
          trend="up"
          description="Awaiting customer response"
        />
        <StatCard
          title="Revenue This Month"
          value={`$${(stats?.contracts?.revenue || 0).toLocaleString()}`}
          change="+23%"
          icon={DollarSign}
          trend="up"
          description="Strong performance"
        />
        <StatCard
          title="Active Contracts"
          value={stats?.contracts?.active || 0}
          change="→ 0%"
          icon={FileText}
          trend="neutral"
          description="Projects in progress"
        />
      </motion.div>

      {/* Main Content Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Recent Activity */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.4, delay: 0.3 }}
          className="lg:col-span-2"
        >
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Activity className="w-5 h-5" />
                <span>Recent Activity</span>
              </CardTitle>
              <CardDescription>Latest updates across your pipeline</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {[
                  {
                    type: 'lead',
                    message: 'New lead: Jennifer Wilson (Roofing)',
                    time: '5 minutes ago',
                    status: 'new',
                  },
                  {
                    type: 'quote',
                    message: 'Quote Q2C-2024-0002 accepted by Michael Davis',
                    time: '2 hours ago',
                    status: 'success',
                  },
                  {
                    type: 'contract',
                    message: 'Contract CNT-2024-0001 signed and activated',
                    time: '1 day ago',
                    status: 'success',
                  },
                  {
                    type: 'export',
                    message: 'Export to Salesforce failed - authentication issue',
                    time: '2 days ago',
                    status: 'error',
                  },
                ].map((activity, index) => (
                  <div key={index} className="flex items-start space-x-3 p-3 rounded-lg bg-muted/30">
                    <div className={`w-2 h-2 rounded-full mt-2 ${
                      activity.status === 'new' ? 'bg-blue-500' :
                      activity.status === 'success' ? 'bg-green-500' :
                      activity.status === 'error' ? 'bg-red-500' : 'bg-gray-500'
                    }`} />
                    <div className="flex-1 space-y-1">
                      <p className="text-sm">{activity.message}</p>
                      <p className="text-xs text-muted-foreground">{activity.time}</p>
                    </div>
                    <Badge 
                      variant={
                        activity.status === 'success' ? 'success' :
                        activity.status === 'error' ? 'destructive' :
                        'secondary'
                      }
                      className="capitalize"
                    >
                      {activity.type}
                    </Badge>
                  </div>
                ))}
              </div>
              <div className="mt-4">
                <Link href="/activity">
                  <Button variant="outline" className="w-full">
                    View All Activity
                  </Button>
                </Link>
              </div>
            </CardContent>
          </Card>
        </motion.div>

        {/* Quick Stats & Alerts */}
        <motion.div
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.4, delay: 0.4 }}
          className="space-y-6"
        >
          {/* Performance Summary */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Target className="w-5 h-5" />
                <span>Performance</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex justify-between items-center">
                <span className="text-sm">Conversion Rate</span>
                <span className="font-semibold">68%</span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div className="bg-green-500 h-2 rounded-full" style={{ width: '68%' }} />
              </div>
              
              <div className="flex justify-between items-center">
                <span className="text-sm">Quote Win Rate</span>
                <span className="font-semibold">45%</span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div className="bg-blue-500 h-2 rounded-full" style={{ width: '45%' }} />
              </div>

              <div className="flex justify-between items-center">
                <span className="text-sm">Avg Response Time</span>
                <span className="font-semibold">2.5h</span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div className="bg-yellow-500 h-2 rounded-full" style={{ width: '75%' }} />
              </div>
            </CardContent>
          </Card>

          {/* Alerts & Notifications */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <AlertTriangle className="w-5 h-5" />
                <span>Alerts</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="p-3 rounded-lg bg-yellow-50 border border-yellow-200">
                <div className="flex items-center space-x-2">
                  <Clock className="w-4 h-4 text-yellow-600" />
                  <span className="text-sm font-medium">Quote Expiring Soon</span>
                </div>
                <p className="text-xs text-yellow-700 mt-1">
                  Quote Q2C-2024-0001 expires in 3 days
                </p>
              </div>

              <div className="p-3 rounded-lg bg-green-50 border border-green-200">
                <div className="flex items-center space-x-2">
                  <CheckCircle className="w-4 h-4 text-green-600" />
                  <span className="text-sm font-medium">SLA On Track</span>
                </div>
                <p className="text-xs text-green-700 mt-1">
                  All active projects meeting deadlines
                </p>
              </div>

              <div className="p-3 rounded-lg bg-blue-50 border border-blue-200">
                <div className="flex items-center space-x-2">
                  <Award className="w-4 h-4 text-blue-600" />
                  <span className="text-sm font-medium">Top Performer</span>
                </div>
                <p className="text-xs text-blue-700 mt-1">
                  Crystal Clear Pools - 5 contracts this month
                </p>
              </div>
            </CardContent>
          </Card>
        </motion.div>
      </div>
    </div>
  );
}
