'use client';

import { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Plus,
  Search,
  Filter,
  Flame,
  ThermometerSun,
  Snowflake,
  Mail,
  Phone,
  Building2,
  X,
  Loader2,
  ArrowUpRight,
  MoreHorizontal,
} from 'lucide-react';

interface Lead {
  id: string;
  companyName: string | null;
  contactName: string;
  email: string | null;
  phone: string | null;
  source: string | null;
  status: string;
  rating: string | null;
  industry: string | null;
  estimatedValue: number | null;
  notes: string | null;
  createdAt: string;
}

const statusColors: Record<string, string> = {
  new: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
  contacted: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
  qualified: 'bg-green-500/20 text-green-400 border-green-500/30',
  converted: 'bg-brand-secondary/20 text-brand-secondary-light border-brand-secondary/30',
  lost: 'bg-red-500/20 text-red-400 border-red-500/30',
};

const ratingIcons: Record<string, React.ComponentType<{ className?: string }>> = {
  hot: Flame,
  warm: ThermometerSun,
  cold: Snowflake,
};

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

export default function LeadsPage() {
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState('');
  const [filterRating, setFilterRating] = useState('');
  const [modalOpen, setModalOpen] = useState(false);
  const [saving, setSaving] = useState(false);

  const [form, setForm] = useState({
    contactName: '',
    companyName: '',
    email: '',
    phone: '',
    source: 'website',
    rating: 'warm',
    industry: '',
    estimatedValue: '',
    notes: '',
  });

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

  useEffect(() => {
    fetchLeads();

    // Check for ?new=1 param
    const params = new URLSearchParams(window.location.search);
    if (params.get('new') === '1') {
      setModalOpen(true);
      window.history.replaceState({}, '', '/apps/crm/leads');
    }
  }, []);

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

    try {
      const res = await fetch('/api/erp/crm', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'lead',
          data: {
            ...form,
            estimatedValue: form.estimatedValue ? parseFloat(form.estimatedValue) : null,
          },
        }),
      });

      if (res.ok) {
        setModalOpen(false);
        setForm({
          contactName: '',
          companyName: '',
          email: '',
          phone: '',
          source: 'website',
          rating: 'warm',
          industry: '',
          estimatedValue: '',
          notes: '',
        });
        fetchLeads();
      }
    } catch (err) {
      console.error('Failed to create lead:', err);
    } finally {
      setSaving(false);
    }
  };

  const filteredLeads = leads.filter((lead) => {
    const matchesSearch =
      lead.contactName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (lead.companyName?.toLowerCase() || '').includes(searchTerm.toLowerCase()) ||
      (lead.email?.toLowerCase() || '').includes(searchTerm.toLowerCase());
    const matchesStatus = !filterStatus || lead.status === filterStatus;
    const matchesRating = !filterRating || lead.rating === filterRating;
    return matchesSearch && matchesStatus && matchesRating;
  });

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

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Leads</h1>
          <p className="text-gray-400">Track and manage your sales leads</p>
        </div>
        <button
          onClick={() => setModalOpen(true)}
          className="flex items-center gap-2 bg-gradient-to-r from-brand-deep to-brand-secondary-deep text-white px-4 py-2 rounded-lg hover:opacity-90 transition-opacity"
        >
          <Plus className="w-5 h-5" />
          New Lead
        </button>
      </div>

      {/* Filters */}
      <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl p-4">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search leads..."
              className="w-full pl-10 pr-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-brand-deep/50"
            />
          </div>
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
            className="px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
          >
            <option value="">All Statuses</option>
            <option value="new">New</option>
            <option value="contacted">Contacted</option>
            <option value="qualified">Qualified</option>
            <option value="converted">Converted</option>
            <option value="lost">Lost</option>
          </select>
          <select
            value={filterRating}
            onChange={(e) => setFilterRating(e.target.value)}
            className="px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
          >
            <option value="">All Ratings</option>
            <option value="hot">🔥 Hot</option>
            <option value="warm">☀️ Warm</option>
            <option value="cold">❄️ Cold</option>
          </select>
        </div>
      </div>

      {/* Leads Table */}
      <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-brand-bg-surface/30 bg-white/5">
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Contact</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Company</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Source</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Rating</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Status</th>
                <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Value</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-brand-bg-surface/20">
              {filteredLeads.length === 0 ? (
                <tr>
                  <td colSpan={7} className="py-12 text-center text-gray-500">
                    No leads found
                  </td>
                </tr>
              ) : (
                filteredLeads.map((lead) => {
                  const RatingIcon = lead.rating ? ratingIcons[lead.rating] : null;
                  return (
                    <tr key={lead.id} className="hover:bg-white/5 transition-colors">
                      <td className="py-3 px-4">
                        <p className="font-medium text-white">{lead.contactName}</p>
                        <div className="flex items-center gap-3 text-xs text-gray-500 mt-1">
                          {lead.email && (
                            <span className="flex items-center gap-1">
                              <Mail className="w-3 h-3" /> {lead.email}
                            </span>
                          )}
                          {lead.phone && (
                            <span className="flex items-center gap-1">
                              <Phone className="w-3 h-3" /> {lead.phone}
                            </span>
                          )}
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        {lead.companyName ? (
                          <span className="flex items-center gap-2 text-gray-300">
                            <Building2 className="w-4 h-4 text-gray-500" />
                            {lead.companyName}
                          </span>
                        ) : (
                          <span className="text-gray-600">-</span>
                        )}
                      </td>
                      <td className="py-3 px-4 text-gray-400 capitalize">{lead.source || '-'}</td>
                      <td className="py-3 px-4 text-center">
                        {RatingIcon && (
                          <RatingIcon className={`w-5 h-5 mx-auto ${ratingColors[lead.rating!]}`} />
                        )}
                      </td>
                      <td className="py-3 px-4 text-center">
                        <span className={`inline-flex px-2 py-1 rounded-full text-xs border ${statusColors[lead.status]}`}>
                          {lead.status}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-right text-gray-300">
                        {lead.estimatedValue ? `$${lead.estimatedValue.toLocaleString()}` : '-'}
                      </td>
                      <td className="py-3 px-4 text-center">
                        <button className="p-1 text-gray-500 hover:text-brand">
                          <MoreHorizontal className="w-5 h-5" />
                        </button>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* New Lead Modal */}
      <AnimatePresence>
        {modalOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4"
            onClick={() => setModalOpen(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-bg-surface/30 rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="flex items-center justify-between p-5 border-b border-brand-bg-surface/30">
                <h2 className="text-lg font-semibold text-white">New Lead</h2>
                <button onClick={() => setModalOpen(false)} className="text-gray-500 hover:text-white">
                  <X className="w-5 h-5" />
                </button>
              </div>

              <form onSubmit={handleSubmit} className="p-5 space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div className="col-span-2">
                    <label className="block text-sm text-gray-400 mb-1">Contact Name *</label>
                    <input
                      type="text"
                      value={form.contactName}
                      onChange={(e) => setForm({ ...form, contactName: e.target.value })}
                      className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                      required
                    />
                  </div>
                  <div className="col-span-2">
                    <label className="block text-sm text-gray-400 mb-1">Company Name</label>
                    <input
                      type="text"
                      value={form.companyName}
                      onChange={(e) => setForm({ ...form, companyName: e.target.value })}
                      className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                    />
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Email</label>
                    <input
                      type="email"
                      value={form.email}
                      onChange={(e) => setForm({ ...form, email: e.target.value })}
                      className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                    />
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Phone</label>
                    <input
                      type="tel"
                      value={form.phone}
                      onChange={(e) => setForm({ ...form, phone: e.target.value })}
                      className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                    />
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Source</label>
                    <select
                      value={form.source}
                      onChange={(e) => setForm({ ...form, source: e.target.value })}
                      className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                    >
                      <option value="website">Website</option>
                      <option value="referral">Referral</option>
                      <option value="cold-call">Cold Call</option>
                      <option value="event">Event</option>
                      <option value="social">Social Media</option>
                      <option value="other">Other</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Rating</label>
                    <select
                      value={form.rating}
                      onChange={(e) => setForm({ ...form, rating: e.target.value })}
                      className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                    >
                      <option value="hot">🔥 Hot</option>
                      <option value="warm">☀️ Warm</option>
                      <option value="cold">❄️ Cold</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Industry</label>
                    <input
                      type="text"
                      value={form.industry}
                      onChange={(e) => setForm({ ...form, industry: e.target.value })}
                      className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                    />
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Estimated Value</label>
                    <input
                      type="number"
                      value={form.estimatedValue}
                      onChange={(e) => setForm({ ...form, estimatedValue: e.target.value })}
                      className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                      placeholder="$"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm text-gray-400 mb-1">Notes</label>
                  <textarea
                    value={form.notes}
                    onChange={(e) => setForm({ ...form, notes: e.target.value })}
                    className="w-full px-4 py-2 bg-white/5 border border-brand-bg-surface/30 rounded-lg text-white focus:outline-none focus:border-brand-deep/50"
                    rows={3}
                  />
                </div>

                <div className="flex gap-3 pt-4">
                  <button
                    type="button"
                    onClick={() => setModalOpen(false)}
                    className="flex-1 px-4 py-2 border border-brand-bg-surface/30 rounded-lg text-gray-400 hover:text-white hover:border-gray-500 transition-colors"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={saving}
                    className="flex-1 px-4 py-2 bg-gradient-to-r from-brand-deep to-brand-secondary-deep text-white rounded-lg hover:opacity-90 disabled:opacity-50 flex items-center justify-center gap-2"
                  >
                    {saving && <Loader2 className="w-4 h-4 animate-spin" />}
                    Create Lead
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
