'use client';

import { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Plus,
  DollarSign,
  Calendar,
  Building2,
  X,
  Loader2,
  MoreHorizontal,
  ChevronRight,
  Percent,
  GripVertical,
} from 'lucide-react';

interface Opportunity {
  id: string;
  name: string;
  customerId: string;
  stage: string;
  probability: number;
  expectedValue: number;
  expectedClose: string | null;
  description: string | null;
  customer: { name: string };
}

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

const stages = [
  { id: 'prospecting', label: 'Prospecting', color: 'border-gray-500', bg: 'bg-gray-500/10' },
  { id: 'qualification', label: 'Qualification', color: 'border-blue-500', bg: 'bg-blue-500/10' },
  { id: 'proposal', label: 'Proposal', color: 'border-yellow-500', bg: 'bg-yellow-500/10' },
  { id: 'negotiation', label: 'Negotiation', color: 'border-orange-500', bg: 'bg-orange-500/10' },
  { id: 'closed-won', label: 'Won', color: 'border-green-500', bg: 'bg-green-500/10' },
  { id: 'closed-lost', label: 'Lost', color: 'border-red-500', bg: 'bg-red-500/10' },
];

const defaultProbabilities: Record<string, number> = {
  prospecting: 10,
  qualification: 25,
  proposal: 50,
  negotiation: 75,
  'closed-won': 100,
  'closed-lost': 0,
};

export default function OpportunitiesPage() {
  const [opportunities, setOpportunities] = useState<Opportunity[]>([]);
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [viewMode, setViewMode] = useState<'pipeline' | 'list'>('pipeline');

  const [form, setForm] = useState({
    name: '',
    customerId: '',
    stage: 'prospecting',
    probability: 10,
    expectedValue: '',
    expectedClose: '',
    description: '',
  });

  const fetchData = async () => {
    try {
      const [oppRes, custRes] = await Promise.all([
        fetch('/api/erp/crm?type=opportunities'),
        fetch('/api/erp/crm?type=customers'),
      ]);

      if (oppRes.ok) {
        const data = await oppRes.json();
        setOpportunities(data.opportunities || []);
      }
      if (custRes.ok) {
        const data = await custRes.json();
        setCustomers(data.customers || []);
      }
    } catch (err) {
      console.error('Failed to fetch data:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();

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

  const handleStageChange = (stage: string) => {
    setForm({
      ...form,
      stage,
      probability: defaultProbabilities[stage] || 10,
    });
  };

  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: 'opportunity',
          data: {
            ...form,
            expectedValue: parseFloat(form.expectedValue) || 0,
            probability: parseInt(String(form.probability)) || 10,
            expectedClose: form.expectedClose || null,
          },
        }),
      });

      if (res.ok) {
        setModalOpen(false);
        setForm({
          name: '',
          customerId: '',
          stage: 'prospecting',
          probability: 10,
          expectedValue: '',
          expectedClose: '',
          description: '',
        });
        fetchData();
      }
    } catch (err) {
      console.error('Failed to create opportunity:', err);
    } finally {
      setSaving(false);
    }
  };

  const getOpportunitiesByStage = (stageId: string) =>
    opportunities.filter((o) => o.stage === stageId);

  const getStageTotal = (stageId: string) =>
    getOpportunitiesByStage(stageId).reduce((sum, o) => sum + o.expectedValue, 0);

  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 pipelineTotal = opportunities
    .filter((o) => !['closed-won', 'closed-lost'].includes(o.stage))
    .reduce((sum, o) => sum + o.expectedValue * (o.probability / 100), 0);

  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">Opportunities</h1>
          <p className="text-gray-400">
            Weighted Pipeline: <span className="text-green-400 font-semibold">${pipelineTotal.toLocaleString()}</span>
          </p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex bg-white/5 border border-brand-bg-surface/30 rounded-lg p-1">
            <button
              onClick={() => setViewMode('pipeline')}
              className={`px-3 py-1 rounded text-sm transition-colors ${
                viewMode === 'pipeline' ? 'bg-brand-deep/20 text-brand' : 'text-gray-500 hover:text-white'
              }`}
            >
              Pipeline
            </button>
            <button
              onClick={() => setViewMode('list')}
              className={`px-3 py-1 rounded text-sm transition-colors ${
                viewMode === 'list' ? 'bg-brand-deep/20 text-brand' : 'text-gray-500 hover:text-white'
              }`}
            >
              List
            </button>
          </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 Opportunity
          </button>
        </div>
      </div>

      {/* Pipeline View */}
      {viewMode === 'pipeline' && (
        <div className="overflow-x-auto pb-4">
          <div className="flex gap-4 min-w-max">
            {stages.slice(0, 4).map((stage) => (
              <div
                key={stage.id}
                className={`w-72 bg-brand-bg-elevated border-t-2 ${stage.color} rounded-xl flex flex-col`}
              >
                <div className="p-4 border-b border-brand-bg-surface/30">
                  <div className="flex items-center justify-between">
                    <h3 className="font-semibold text-white">{stage.label}</h3>
                    <span className="text-xs text-gray-500">
                      {getOpportunitiesByStage(stage.id).length} deals
                    </span>
                  </div>
                  <p className="text-sm text-green-400 mt-1">
                    ${getStageTotal(stage.id).toLocaleString()}
                  </p>
                </div>

                <div className="p-3 space-y-3 flex-1 overflow-y-auto max-h-[500px]">
                  {getOpportunitiesByStage(stage.id).map((opp) => (
                    <motion.div
                      key={opp.id}
                      layout
                      className="bg-white/5 border border-brand-bg-surface/30 rounded-lg p-3 hover:border-brand-deep/50 transition-all cursor-pointer group"
                    >
                      <div className="flex items-start justify-between mb-2">
                        <p className="font-medium text-white text-sm truncate flex-1">{opp.name}</p>
                        <button className="p-1 text-gray-600 hover:text-brand opacity-0 group-hover:opacity-100 transition-opacity">
                          <MoreHorizontal className="w-4 h-4" />
                        </button>
                      </div>
                      <p className="text-xs text-gray-500 flex items-center gap-1 mb-2">
                        <Building2 className="w-3 h-3" /> {opp.customer.name}
                      </p>
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-green-400 font-medium">
                          ${opp.expectedValue.toLocaleString()}
                        </span>
                        <span className="text-xs text-gray-500">{opp.probability}%</span>
                      </div>
                      {opp.expectedClose && (
                        <p className="text-xs text-gray-600 mt-2 flex items-center gap-1">
                          <Calendar className="w-3 h-3" />
                          {new Date(opp.expectedClose).toLocaleDateString()}
                        </p>
                      )}
                    </motion.div>
                  ))}

                  {getOpportunitiesByStage(stage.id).length === 0 && (
                    <div className="py-8 text-center text-gray-600 text-sm">
                      No deals in this stage
                    </div>
                  )}
                </div>
              </div>
            ))}

            {/* Won/Lost Combined */}
            <div className="w-72 space-y-4">
              {stages.slice(4).map((stage) => (
                <div
                  key={stage.id}
                  className={`bg-brand-bg-elevated border-t-2 ${stage.color} rounded-xl`}
                >
                  <div className="p-3 border-b border-brand-bg-surface/30">
                    <div className="flex items-center justify-between">
                      <h3 className="font-medium text-white text-sm">{stage.label}</h3>
                      <span className="text-xs text-gray-500">
                        {getOpportunitiesByStage(stage.id).length}
                      </span>
                    </div>
                    <p className="text-xs text-gray-500 mt-0.5">
                      ${getStageTotal(stage.id).toLocaleString()}
                    </p>
                  </div>
                  <div className="p-2 max-h-32 overflow-y-auto">
                    {getOpportunitiesByStage(stage.id).slice(0, 3).map((opp) => (
                      <div key={opp.id} className="p-2 text-xs text-gray-400 truncate">
                        {opp.name}
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* List View */}
      {viewMode === 'list' && (
        <div className="bg-brand-bg-elevated border border-brand-bg-surface/30 rounded-xl overflow-hidden">
          <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">Opportunity</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-400">Customer</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Stage</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-400">Probability</th>
                <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Value</th>
                <th className="text-right py-3 px-4 text-sm font-medium text-gray-400">Close Date</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-brand-bg-surface/20">
              {opportunities.map((opp) => {
                const stage = stages.find((s) => s.id === opp.stage);
                return (
                  <tr key={opp.id} className="hover:bg-white/5 transition-colors">
                    <td className="py-3 px-4 font-medium text-white">{opp.name}</td>
                    <td className="py-3 px-4 text-gray-400">{opp.customer.name}</td>
                    <td className="py-3 px-4 text-center">
                      <span className={`inline-flex px-2 py-1 rounded text-xs border-l-2 ${stage?.color} ${stage?.bg}`}>
                        {stage?.label}
                      </span>
                    </td>
                    <td className="py-3 px-4 text-center text-gray-400">{opp.probability}%</td>
                    <td className="py-3 px-4 text-right text-green-400 font-medium">
                      ${opp.expectedValue.toLocaleString()}
                    </td>
                    <td className="py-3 px-4 text-right text-gray-500">
                      {opp.expectedClose ? new Date(opp.expectedClose).toLocaleDateString() : '-'}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* New Opportunity 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"
              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 Opportunity</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>
                  <label className="block text-sm text-gray-400 mb-1">Opportunity Name *</label>
                  <input
                    type="text"
                    value={form.name}
                    onChange={(e) => setForm({ ...form, name: 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="e.g., Enterprise License Deal"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm text-gray-400 mb-1">Customer *</label>
                  <select
                    value={form.customerId}
                    onChange={(e) => setForm({ ...form, customerId: 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
                  >
                    <option value="">Select a 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 text-gray-400 mb-1">Stage</label>
                    <select
                      value={form.stage}
                      onChange={(e) => handleStageChange(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"
                    >
                      {stages.slice(0, 4).map((s) => (
                        <option key={s.id} value={s.id}>{s.label}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Probability (%)</label>
                    <input
                      type="number"
                      min="0"
                      max="100"
                      value={form.probability}
                      onChange={(e) => setForm({ ...form, probability: parseInt(e.target.value) || 0 })}
                      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>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Expected Value *</label>
                    <input
                      type="number"
                      value={form.expectedValue}
                      onChange={(e) => setForm({ ...form, expectedValue: 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="$"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-sm text-gray-400 mb-1">Expected Close</label>
                    <input
                      type="date"
                      value={form.expectedClose}
                      onChange={(e) => setForm({ ...form, expectedClose: 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>

                <div>
                  <label className="block text-sm text-gray-400 mb-1">Description</label>
                  <textarea
                    value={form.description}
                    onChange={(e) => setForm({ ...form, description: 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 Opportunity
                  </button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
