'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Target, Plus, Search, Mail, Phone, Building2,
  DollarSign, Calendar, User, X, Loader2, ArrowRight,
  CheckCircle, Clock, AlertCircle
} from 'lucide-react';

interface Lead {
  id: string;
  companyName?: string;
  contactName?: string;
  email?: string;
  phone?: string;
  source?: string;
  status: string;
  estimatedValue?: number;
  notes?: string;
  createdAt: string;
  customer?: { id: string; name: string };
  assignedTo?: { id: string; firstName: string; lastName: string };
}

const statusConfig: Record<string, { color: string; icon: any; label: string }> = {
  new: { color: 'text-blue-400 bg-blue-500/20', icon: AlertCircle, label: 'New' },
  contacted: { color: 'text-amber-400 bg-amber-500/20', icon: Clock, label: 'Contacted' },
  qualified: { color: 'text-orange-400 bg-orange-500/20', icon: CheckCircle, label: 'Qualified' },
  converted: { color: 'text-green-400 bg-green-500/20', icon: CheckCircle, label: 'Converted' },
  lost: { color: 'text-red-400 bg-red-500/20', icon: X, label: 'Lost' }
};

export default function LeadsPage() {
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddModal, setShowAddModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [formData, setFormData] = useState({
    companyName: '',
    contactName: '',
    email: '',
    phone: '',
    source: 'website',
    estimatedValue: '',
    notes: ''
  });

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

  const fetchLeads = async () => {
    try {
      const res = await fetch('/api/erp/crm/leads');
      const data = await res.json();
      setLeads(data.leads || []);
    } catch (error) {
      console.error('Failed to fetch leads:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);

    try {
      const res = await fetch('/api/erp/crm/leads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      if (res.ok) {
        setShowAddModal(false);
        setFormData({ companyName: '', contactName: '', email: '', phone: '', source: 'website', estimatedValue: '', notes: '' });
        fetchLeads();
      }
    } catch (error) {
      console.error('Failed to create lead:', error);
    } finally {
      setSaving(false);
    }
  };

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

  // Group leads by status
  const leadsByStatus = leads.reduce((acc, lead) => {
    const status = lead.status || 'new';
    if (!acc[status]) acc[status] = [];
    acc[status].push(lead);
    return acc;
  }, {} as Record<string, Lead[]>);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-amber-500/20">
            <Target className="w-6 h-6 text-amber-400" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">Leads</h1>
            <p className="text-gray-400">{leads.length} total leads</p>
          </div>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg flex items-center gap-2 transition-colors"
        >
          <Plus className="w-4 h-4" />
          Add Lead
        </button>
      </div>

      {/* Lead Pipeline */}
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <Loader2 className="w-8 h-8 animate-spin text-amber-400" />
        </div>
      ) : leads.length === 0 ? (
        <div className="glass-card p-12 text-center">
          <Target className="w-16 h-16 text-gray-600 mx-auto mb-4" />
          <h3 className="text-xl font-semibold text-white mb-2">No Leads Yet</h3>
          <p className="text-gray-400 mb-6">Start capturing leads for your pipeline</p>
          <button
            onClick={() => setShowAddModal(true)}
            className="px-6 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg"
          >
            Add Your First Lead
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {['new', 'contacted', 'qualified', 'converted'].map((status) => {
            const config = statusConfig[status];
            const statusLeads = leadsByStatus[status] || [];

            return (
              <div key={status} className="space-y-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className={`p-1.5 rounded ${config.color}`}>
                      <config.icon className="w-4 h-4" />
                    </span>
                    <span className="font-medium text-white">{config.label}</span>
                  </div>
                  <span className="text-sm text-gray-500">{statusLeads.length}</span>
                </div>

                <div className="space-y-2 min-h-[200px]">
                  {statusLeads.map((lead, idx) => (
                    <motion.div
                      key={lead.id}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: idx * 0.05 }}
                      className="glass-card p-3 hover:border-amber-500/30 transition-colors cursor-pointer"
                    >
                      <h4 className="font-medium text-white text-sm mb-1">
                        {lead.companyName || lead.contactName}
                      </h4>
                      {lead.contactName && lead.companyName && (
                        <p className="text-xs text-gray-400 flex items-center gap-1">
                          <User className="w-3 h-3" />
                          {lead.contactName}
                        </p>
                      )}
                      {lead.email && (
                        <p className="text-xs text-gray-500 flex items-center gap-1 mt-1">
                          <Mail className="w-3 h-3" />
                          {lead.email}
                        </p>
                      )}
                      {lead.estimatedValue && (
                        <p className="text-xs text-amber-400 mt-2">
                          {formatCurrency(lead.estimatedValue)}
                        </p>
                      )}
                      <div className="mt-2 pt-2 border-t border-brand-deep/20">
                        <span className="text-xs text-gray-500 capitalize">{lead.source}</span>
                      </div>
                    </motion.div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Add Lead Modal */}
      <AnimatePresence>
        {showAddModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
            onClick={() => setShowAddModal(false)}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-brand-bg-elevated border border-brand-deep/30 rounded-xl w-full max-w-md"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="p-6">
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold text-white">Add New Lead</h2>
                  <button onClick={() => setShowAddModal(false)} className="p-1 text-gray-400 hover:text-white">
                    <X className="w-5 h-5" />
                  </button>
                </div>

                <form onSubmit={handleSubmit} className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Company Name</label>
                    <input
                      type="text"
                      value={formData.companyName}
                      onChange={(e) => setFormData({ ...formData, companyName: e.target.value })}
                      className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-amber-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Contact Name</label>
                    <input
                      type="text"
                      value={formData.contactName}
                      onChange={(e) => setFormData({ ...formData, contactName: e.target.value })}
                      className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-amber-500"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Email</label>
                      <input
                        type="email"
                        value={formData.email}
                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-amber-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Phone</label>
                      <input
                        type="tel"
                        value={formData.phone}
                        onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-amber-500"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Source</label>
                      <select
                        value={formData.source}
                        onChange={(e) => setFormData({ ...formData, source: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-amber-500"
                      >
                        <option value="website">Website</option>
                        <option value="referral">Referral</option>
                        <option value="linkedin">LinkedIn</option>
                        <option value="cold_call">Cold Call</option>
                        <option value="conference">Conference</option>
                        <option value="other">Other</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Est. Value</label>
                      <input
                        type="number"
                        value={formData.estimatedValue}
                        onChange={(e) => setFormData({ ...formData, estimatedValue: e.target.value })}
                        className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-amber-500"
                        placeholder="$"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Notes</label>
                    <textarea
                      value={formData.notes}
                      onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                      rows={3}
                      className="w-full px-3 py-2 bg-brand-bg border border-brand-deep/30 rounded-lg text-white focus:outline-none focus:border-amber-500 resize-none"
                    />
                  </div>

                  <div className="flex justify-end gap-3 pt-4">
                    <button
                      type="button"
                      onClick={() => setShowAddModal(false)}
                      className="px-4 py-2 border border-brand-deep/30 rounded-lg text-gray-300 hover:text-white"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      disabled={saving}
                      className="px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white rounded-lg flex items-center gap-2 disabled:opacity-50"
                    >
                      {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                      Add Lead
                    </button>
                  </div>
                </form>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
