'use client';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  DollarSign,
  Users,
  Target,
  TrendingUp,
  FileText,
  ArrowRight,
  Loader2,
  Flame,
  Clock,
  Building2,
  ChevronRight,
} from 'lucide-react';

interface CRMSummary {
  totalCustomers: number;
  activeLeads: number;
  hotLeads: number;
  openOpportunities: number;
  pipelineValue: number;
  pendingQuotes: number;
  pendingQuotesValue: number;
  openOrders: number;
  openOrdersValue: number;
}

interface Lead {
  id: string;
  companyName: string | null;
  contactName: string;
  email: string | null;
  status: string;
  rating: string | null;
  createdAt: string;
}

interface Opportunity {
  id: string;
  name: string;
  stage: string;
  expectedValue: number;
  probability: number;
  customer: { name: string };
}

const stageColors: Record<string, string> = {
  prospecting: 'bg-gray-500',
  qualification: 'bg-blue-500',
  proposal: 'bg-yellow-500',
  negotiation: 'bg-orange-500',
  'closed-won': 'bg-green-500',
  'closed-lost': 'bg-red-500',
};

const ratingColors: Record<string, string> = {
  hot: 'text-red-400 bg-red-500/20',
  warm: 'text-orange-400 bg-orange-500/20',
  cold: 'text-blue-400 bg-blue-500/20',
};

export default function CRMDashboard() {
  const [summary, setSummary] = useState<CRMSummary | null>(null);
  const [recentLeads, setRecentLeads] = useState<Lead[]>([]);
  const [topOpportunities, setTopOpportunities] = useState<Opportunity[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch('/api/erp/crm?type=summary');
        if (res.ok) {
          const data = await res.json();
          setSummary(data.summary);
          setRecentLeads(data.recentLeads || []);
          setTopOpportunities(data.topOpportunities || []);
        }
      } catch (err) {
        console.error('Failed to fetch CRM data:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

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

  const stats = [
    {
      label: 'Pipeline Value',
      value: `$${((summary?.pipelineValue || 0) / 1000).toFixed(0)}k`,
      icon: DollarSign,
      color: 'from-green-500 to-emerald-600',
      href: '/apps/crm/opportunities',
    },
    {
      label: 'Active Leads',
      value: summary?.activeLeads || 0,
      icon: Target,
      color: 'from-brand-deep to-blue-600',
      href: '/apps/crm/leads',
      badge: summary?.hotLeads ? `${summary.hotLeads} hot` : undefined,
    },
    {
      label: 'Open Opportunities',
      value: summary?.openOpportunities || 0,
      icon: TrendingUp,
      color: 'from-brand-secondary to-pink-600',
      href: '/apps/crm/opportunities',
    },
    {
      label: 'Customers',
      value: summary?.totalCustomers || 0,
      icon: Building2,
      color: 'from-orange-500 to-red-600',
      href: '/apps/crm/customers',
    },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Sales Dashboard</h1>
        <p className="text-gray-400">Track your pipeline, leads, and opportunities</p>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat, idx) => {
          const Icon = stat.icon;
          return (
            <motion.div
              key={stat.label}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: idx * 0.1 }}
            >
              <Link
                href={stat.href}
                className="block bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl p-5 hover:border-brand-deep/50 transition-all group"
              >
                <div className="flex items-start justify-between">
                  <div>
                    <p className="text-sm text-gray-400">{stat.label}</p>
                    <p className="text-2xl font-bold text-white mt-1">{stat.value}</p>
                    {stat.badge && (
                      <span className="inline-flex items-center gap-1 mt-2 px-2 py-0.5 rounded-full bg-red-500/20 text-red-400 text-xs">
                        <Flame className="w-3 h-3" /> {stat.badge}
                      </span>
                    )}
                  </div>
                  <div className={`bg-gradient-to-br ${stat.color} p-3 rounded-lg`}>
                    <Icon className="w-5 h-5 text-white" />
                  </div>
                </div>
                <div className="mt-3 flex items-center text-sm text-brand opacity-0 group-hover:opacity-100 transition-opacity">
                  View details <ChevronRight className="w-4 h-4 ml-1" />
                </div>
              </Link>
            </motion.div>
          );
        })}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Leads */}
        <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl">
          <div className="flex items-center justify-between p-5 border-b border-brand-bg-surface/30">
            <h2 className="font-semibold text-white flex items-center gap-2">
              <Target className="w-5 h-5 text-brand" /> Recent Leads
            </h2>
            <Link
              href="/apps/crm/leads"
              className="text-sm text-brand hover:text-brand-light flex items-center gap-1"
            >
              View All <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
          <div className="divide-y divide-brand-bg-surface/20">
            {recentLeads.length === 0 ? (
              <div className="p-8 text-center text-gray-500">No leads yet</div>
            ) : (
              recentLeads.map((lead) => (
                <div key={lead.id} className="p-4 hover:bg-white/5 transition-colors">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-white">{lead.contactName}</p>
                      <p className="text-sm text-gray-400">{lead.companyName || lead.email}</p>
                    </div>
                    <div className="flex items-center gap-2">
                      {lead.rating && (
                        <span className={`px-2 py-0.5 rounded-full text-xs ${ratingColors[lead.rating] || 'bg-gray-500/20 text-gray-400'}`}>
                          {lead.rating}
                        </span>
                      )}
                      <span className="text-xs text-gray-500">
                        {new Date(lead.createdAt).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Top Opportunities */}
        <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl">
          <div className="flex items-center justify-between p-5 border-b border-brand-bg-surface/30">
            <h2 className="font-semibold text-white flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-brand-secondary-light" /> Top Opportunities
            </h2>
            <Link
              href="/apps/crm/opportunities"
              className="text-sm text-brand hover:text-brand-light flex items-center gap-1"
            >
              View All <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
          <div className="divide-y divide-brand-bg-surface/20">
            {topOpportunities.length === 0 ? (
              <div className="p-8 text-center text-gray-500">No opportunities yet</div>
            ) : (
              topOpportunities.map((opp) => (
                <div key={opp.id} className="p-4 hover:bg-white/5 transition-colors">
                  <div className="flex items-center justify-between mb-2">
                    <div>
                      <p className="font-medium text-white">{opp.name}</p>
                      <p className="text-sm text-gray-400">{opp.customer.name}</p>
                    </div>
                    <p className="font-semibold text-green-400">
                      ${opp.expectedValue.toLocaleString()}
                    </p>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className={`w-2 h-2 rounded-full ${stageColors[opp.stage] || 'bg-gray-500'}`} />
                    <span className="text-xs text-gray-400 capitalize">{opp.stage.replace('-', ' ')}</span>
                    <span className="text-xs text-gray-500">•</span>
                    <span className="text-xs text-gray-400">{opp.probability}% probability</span>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {[
          { label: 'New Lead', href: '/apps/crm/leads?new=1', icon: Target },
          { label: 'New Customer', href: '/apps/crm/customers?new=1', icon: Building2 },
          { label: 'New Opportunity', href: '/apps/crm/opportunities?new=1', icon: TrendingUp },
          { label: 'New Quote', href: '/apps/crm/quotes?new=1', icon: FileText },
        ].map((action) => {
          const Icon = action.icon;
          return (
            <Link
              key={action.label}
              href={action.href}
              className="flex items-center gap-3 p-4 bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl hover:border-brand-deep/50 transition-all group"
            >
              <div className="p-2 rounded-lg bg-brand-deep/10 group-hover:bg-brand-deep/20 transition-colors">
                <Icon className="w-5 h-5 text-brand" />
              </div>
              <span className="text-sm font-medium text-gray-300 group-hover:text-white">{action.label}</span>
            </Link>
          );
        })}
      </div>
    </div>
  );
}
