'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Handshake, Plus, DollarSign, Calendar, User, X, Loader2,
  TrendingUp, Building2, Percent, CheckCircle, Clock
} from 'lucide-react';

interface Opportunity {
  id: string;
  name: string;
  value?: number;
  probability?: number;
  status: string;
  expectedCloseDate?: string;
  notes?: string;
  createdAt: string;
  customer?: { id: string; name: string; customerNumber: string };
  contact?: { id: string; firstName: string; lastName: string; email: string };
}

interface Customer {
  id: string;
  name: string;
  customerNumber: string;
}

const stageConfig: Record<string, { color: string; bgColor: string; label: string }> = {
  qualification: { color: 'text-blue-400', bgColor: 'bg-blue-500/20', label: 'Qualification' },
  proposal: { color: 'text-orange-400', bgColor: 'bg-orange-500/20', label: 'Proposal' },
  negotiation: { color: 'text-amber-400', bgColor: 'bg-amber-500/20', label: 'Negotiation' },
  closed_won: { color: 'text-green-400', bgColor: 'bg-green-500/20', label: 'Closed Won' },
  closed_lost: { color: 'text-red-400', bgColor: 'bg-red-500/20', label: 'Closed Lost' }
};

export default function OpportunitiesPage() {
  const [opportunities, setOpportunities] = useState<Opportunity[]>([]);
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddModal, setShowAddModal] = useState(false);
  const [saving, setSaving] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    customerId: '',
    value: '',
    probability: '50',
    expectedCloseDate: '',
    stage: 'qualification',
    notes: ''
  });

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

  const fetchData = async () => {
    try {
      const [oppsRes, customersRes] = await Promise.all([
        fetch('/api/erp/crm/opportunities'),
        fetch('/api/erp/crm/customers')
      ]);
      const oppsData = await oppsRes.json();
      const customersData = await customersRes.json();
      setOpportunities(oppsData.opportunities || []);
      setCustomers(customersData.customers || []);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

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

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

      if (res.ok) {
        setShowAddModal(false);
        setFormData({ name: '', customerId: '', value: '', probability: '50', expectedCloseDate: '', stage: 'qualification', notes: '' });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to create opportunity:', error);
    } finally {
      setSaving(false);
    }
  };

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

  // Calculate pipeline stats
  const pipelineValue = opportunities
    .filter(o => !['closed_won', 'closed_lost'].includes(o.status))
    .reduce((sum, o) => sum + ((o.value || 0) * ((o.probability || 50) / 100)), 0);

  const wonValue = opportunities
    .filter(o => o.status === 'closed_won')
    .reduce((sum, o) => sum + (o.value || 0), 0);

  // Group opportunities by stage
  const oppsByStage = opportunities.reduce((acc, opp) => {
    const stage = opp.status || 'qualification';
    if (!acc[stage]) acc[stage] = [];
    acc[stage].push(opp);
    return acc;
  }, {} as Record<string, Opportunity[]>);

  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-sky-500/20">
            <Handshake className="w-6 h-6 text-sky-400" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">Opportunities</h1>
            <p className="text-gray-400">{opportunities.length} total opportunities</p>
          </div>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="px-4 py-2 bg-sky-600 hover:bg-sky-700 text-white rounded-lg flex items-center gap-2 transition-colors"
        >
          <Plus className="w-4 h-4" />
          New Opportunity
        </button>
      </div>

      {/* Pipeline Stats */}
      <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-sky-500/10">
              <TrendingUp className="w-5 h-5 text-sky-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Weighted Pipeline</p>
              <p className="text-xl font-bold text-white">{formatCurrency(pipelineValue)}</p>
            </div>
          </div>
        </div>
        <div className="glass-card p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-green-500/10">
              <CheckCircle className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Won Revenue</p>
              <p className="text-xl font-bold text-white">{formatCurrency(wonValue)}</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">
              <Handshake className="w-5 h-5 text-orange-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Open Deals</p>
              <p className="text-xl font-bold text-white">
                {opportunities.filter(o => !['closed_won', 'closed_lost'].includes(o.status)).length}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Pipeline Board */}
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <Loader2 className="w-8 h-8 animate-spin text-sky-400" />
        </div>
      ) : opportunities.length === 0 ? (
        <div className="glass-card p-12 text-center">
          <Handshake className="w-16 h-16 text-gray-600 mx-auto mb-4" />
          <h3 className="text-xl font-semibold text-white mb-2">No Opportunities Yet</h3>
          <p className="text-gray-400 mb-6">Start building your sales pipeline</p>
          <button
            onClick={() => setShowAddModal(true)}
            className="px-6 py-2 bg-sky-600 hover:bg-sky-700 text-white rounded-lg"
          >
            Create First Opportunity
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
          {['qualification', 'proposal', 'negotiation', 'closed_won', 'closed_lost'].map((stage) => {
            const config = stageConfig[stage];
            const stageOpps = oppsByStage[stage] || [];
            const stageValue = stageOpps.reduce((sum, o) => sum + (o.value || 0), 0);

            return (
              <div key={stage} className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className={`px-2 py-1 rounded text-sm font-medium ${config.color} ${config.bgColor}`}>
                    {config.label}
                  </span>
                  <span className="text-xs text-gray-500">{formatCurrency(stageValue)}</span>
                </div>

                <div className="space-y-2 min-h-[200px]">
                  {stageOpps.map((opp, idx) => (
                    <motion.div
                      key={opp.id}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: idx * 0.05 }}
                      className="glass-card p-3 hover:border-sky-500/30 transition-colors cursor-pointer"
                    >
                      <h4 className="font-medium text-white text-sm mb-1">{opp.name}</h4>
                      <p className="text-xs text-gray-400 flex items-center gap-1">
                        <Building2 className="w-3 h-3" />
                        {opp.customer?.name || 'No customer'}
                      </p>
                      <div className="flex items-center justify-between mt-2">
                        <span className="text-sm text-sky-400 font-medium">
                          {formatCurrency(opp.value || 0)}
                        </span>
                        <span className="text-xs text-gray-500 flex items-center gap-1">
                          <Percent className="w-3 h-3" />
                          {opp.probability || 50}%
                        </span>
                      </div>
                      {opp.expectedCloseDate && (
                        <p className="text-xs text-gray-500 flex items-center gap-1 mt-2">
                          <Calendar className="w-3 h-3" />
                          {new Date(opp.expectedCloseDate).toLocaleDateString()}
                        </p>
                      )}
                    </motion.div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Add Opportunity 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">New Opportunity</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">Opportunity Name *</label>
                    <input
                      type="text"
                      required
                      value={formData.name}
                      onChange={(e) => setFormData({ ...formData, name: 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-sky-500"
                      placeholder="e.g., Enterprise License Deal"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-1">Customer *</label>
                    <select
                      required
                      value={formData.customerId}
                      onChange={(e) => setFormData({ ...formData, customerId: 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-sky-500"
                    >
                      <option value="">Select Customer</option>
                      {customers.map(c => (
                        <option key={c.id} value={c.id}>{c.name}</option>
                      ))}
                    </select>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Value ($)</label>
                      <input
                        type="number"
                        value={formData.value}
                        onChange={(e) => setFormData({ ...formData, value: 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-sky-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Probability (%)</label>
                      <input
                        type="number"
                        min="0"
                        max="100"
                        value={formData.probability}
                        onChange={(e) => setFormData({ ...formData, probability: 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-sky-500"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Stage</label>
                      <select
                        value={formData.stage}
                        onChange={(e) => setFormData({ ...formData, stage: 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-sky-500"
                      >
                        <option value="qualification">Qualification</option>
                        <option value="proposal">Proposal</option>
                        <option value="negotiation">Negotiation</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-300 mb-1">Expected Close</label>
                      <input
                        type="date"
                        value={formData.expectedCloseDate}
                        onChange={(e) => setFormData({ ...formData, expectedCloseDate: 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-sky-500"
                      />
                    </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-sky-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-sky-600 hover:bg-sky-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" />}
                      Create
                    </button>
                  </div>
                </form>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
