'use client';

import { ATAButton } from '@/components/agent-hierarchy/ata-flyout';
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  TrendingUp, Users, Target, Handshake, DollarSign,
  ArrowUp, ArrowDown, FileSpreadsheet, Loader2, UserCircle,
  Phone, Mail, Calendar, Clock, BarChart3
} from 'lucide-react';
import Link from 'next/link';

interface CRMStats {
  totalCustomers: number;
  activeLeads: number;
  pipelineValue: number;
  totalRevenue: number;
  pendingRevenue: number;
  openOpportunities: number;
  openOrders: number;
}

export default function CRMDashboard() {
  const [stats, setStats] = useState<CRMStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [recentCustomers, setRecentCustomers] = useState<any[]>([]);
  const [recentOpportunities, setRecentOpportunities] = useState<any[]>([]);

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

  const fetchData = async () => {
    try {
      const [statsRes, customersRes, oppsRes] = await Promise.all([
        fetch('/api/erp/crm'),
        fetch('/api/erp/crm/customers?limit=5'),
        fetch('/api/erp/crm/opportunities?limit=5')
      ]);

      const statsData = await statsRes.json();
      const customersData = await customersRes.json();
      const oppsData = await oppsRes.json();

      setStats(statsData.stats);
      setRecentCustomers(customersData.customers || []);
      setRecentOpportunities(oppsData.opportunities || []);
    } catch (error) {
      console.error('Failed to fetch CRM data:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(value);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-brand-primary" />
      </div>
    );
  }

  const statCards = [
    {
      title: 'Total Customers',
      value: stats?.totalCustomers || 0,
      icon: UserCircle,
      color: 'text-pink-400',
      bgColor: 'bg-pink-500/10',
      link: '/ghost-control/operations/crm/customers'
    },
    {
      title: 'Active Leads',
      value: stats?.activeLeads || 0,
      icon: Target,
      color: 'text-amber-400',
      bgColor: 'bg-amber-500/10',
      link: '/ghost-control/operations/crm/leads'
    },
    {
      title: 'Pipeline Value',
      value: formatCurrency(stats?.pipelineValue || 0),
      icon: Handshake,
      color: 'text-sky-400',
      bgColor: 'bg-sky-500/10',
      link: '/ghost-control/operations/crm/opportunities'
    },
    {
      title: 'Total Revenue',
      value: formatCurrency(stats?.totalRevenue || 0),
      icon: DollarSign,
      color: 'text-green-400',
      bgColor: 'bg-green-500/10',
      link: '/ghost-control/operations/crm/orders'
    }
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-pink-500/20">
            <TrendingUp className="w-6 h-6 text-pink-400" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">CRM & Sales</h1>
            <p className="text-gray-400">Nexus • Chief Relationship Officer</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <ATAButton agentId="agent-crm" variant="compact" />
          <Link
            href="/ghost-control/operations/crm/customers"
            className="px-4 py-2 bg-pink-600 hover:bg-pink-700 text-white rounded-lg flex items-center gap-2 transition-colors"
          >
            <Users className="w-4 h-4" />
            New Customer
          </Link>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((stat, idx) => (
          <motion.div
            key={stat.title}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: idx * 0.1 }}
          >
            <Link href={stat.link}>
              <div className="glass-card p-4 hover:border-pink-500/30 transition-colors cursor-pointer">
                <div className="flex items-center justify-between mb-3">
                  <span className="text-gray-400 text-sm">{stat.title}</span>
                  <div className={`p-2 rounded-lg ${stat.bgColor}`}>
                    <stat.icon className={`w-4 h-4 ${stat.color}`} />
                  </div>
                </div>
                <p className="text-2xl font-bold text-white">{stat.value}</p>
              </div>
            </Link>
          </motion.div>
        ))}
      </div>

      {/* Two Column Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Customers */}
        <div className="glass-card p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-white flex items-center gap-2">
              <UserCircle className="w-5 h-5 text-pink-400" />
              Recent Customers
            </h2>
            <Link
              href="/ghost-control/operations/crm/customers"
              className="text-pink-400 hover:text-pink-300 text-sm"
            >
              View All →
            </Link>
          </div>
          <div className="space-y-3">
            {recentCustomers.length === 0 ? (
              <p className="text-gray-500 text-center py-8">No customers yet</p>
            ) : (
              recentCustomers.map((customer: any) => (
                <Link
                  key={customer.id}
                  href={`/ghost-control/operations/crm/customers?id=${customer.id}`}
                  className="block p-3 bg-brand-bg-elevated/50 rounded-lg hover:bg-brand-bg-elevated transition-colors"
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-white">{customer.name}</p>
                      <p className="text-sm text-gray-400">{customer.customerNumber}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-sm text-gray-300">{customer._count?.salesOrders || 0} orders</p>
                      <p className="text-xs text-gray-500">{customer.industry || 'N/A'}</p>
                    </div>
                  </div>
                </Link>
              ))
            )}
          </div>
        </div>

        {/* Pipeline */}
        <div className="glass-card p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-white flex items-center gap-2">
              <Handshake className="w-5 h-5 text-sky-400" />
              Open Opportunities
            </h2>
            <Link
              href="/ghost-control/operations/crm/opportunities"
              className="text-sky-400 hover:text-sky-300 text-sm"
            >
              View All →
            </Link>
          </div>
          <div className="space-y-3">
            {recentOpportunities.length === 0 ? (
              <p className="text-gray-500 text-center py-8">No open opportunities</p>
            ) : (
              recentOpportunities.map((opp: any) => (
                <div
                  key={opp.id}
                  className="p-3 bg-brand-bg-elevated/50 rounded-lg"
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-white">{opp.name}</p>
                      <p className="text-sm text-gray-400">{opp.customer?.name}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-sky-400 font-medium">
                        {formatCurrency(opp.value?.toNumber?.() || opp.value || 0)}
                      </p>
                      <p className="text-xs text-gray-500">{opp.probability}% probability</p>
                    </div>
                  </div>
                  <div className="mt-2 flex items-center gap-2">
                    <div className="flex-1 bg-gray-700 rounded-full h-1.5">
                      <div
                        className="bg-sky-500 h-1.5 rounded-full transition-all"
                        style={{ width: `${opp.probability}%` }}
                      />
                    </div>
                    <span className="text-xs text-gray-400 capitalize">{opp.status}</span>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      {/* Quick Stats Row */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="glass-card p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-amber-500/10">
              <FileSpreadsheet className="w-5 h-5 text-amber-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Open Orders</p>
              <p className="text-xl font-bold text-white">{stats?.openOrders || 0}</p>
            </div>
          </div>
        </div>
        <div className="glass-card p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-orange-500/10">
              <DollarSign className="w-5 h-5 text-orange-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Pending Revenue</p>
              <p className="text-xl font-bold text-white">{formatCurrency(stats?.pendingRevenue || 0)}</p>
            </div>
          </div>
        </div>
        <div className="glass-card p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-sky-500/10">
              <Handshake className="w-5 h-5 text-sky-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Open Opportunities</p>
              <p className="text-xl font-bold text-white">{stats?.openOpportunities || 0}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
