'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  FileSpreadsheet, Plus, Search, DollarSign, Calendar,
  Package, Truck, CheckCircle, Clock, XCircle, Loader2,
  Building2, ChevronDown, ChevronRight, Eye, X, Trash2
} from 'lucide-react';
import Link from 'next/link';

interface SalesOrder {
  id: string;
  orderNumber: string;
  customerId: string;
  status: string;
  subtotal?: number;
  taxAmount?: number;
  totalAmount?: number;
  shippingAddress?: string;
  notes?: string;
  createdAt: string;
  customer?: { id: string; name: string; customerNumber: string };
  items?: any[];
}

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

interface Product {
  id: string;
  sku: string;
  name: string;
  salePrice: number;
  category?: string;
}

interface OrderLineItem {
  productId?: string;
  description: string;
  quantity: number;
  unitPrice: number;
}

const statusConfig: Record<string, { color: string; bgColor: string; icon: any; label: string }> = {
  pending: { color: 'text-amber-400', bgColor: 'bg-amber-500/20', icon: Clock, label: 'Pending' },
  confirmed: { color: 'text-blue-400', bgColor: 'bg-blue-500/20', icon: CheckCircle, label: 'Confirmed' },
  processing: { color: 'text-orange-400', bgColor: 'bg-orange-500/20', icon: Package, label: 'Processing' },
  shipped: { color: 'text-sky-400', bgColor: 'bg-sky-500/20', icon: Truck, label: 'Shipped' },
  completed: { color: 'text-green-400', bgColor: 'bg-green-500/20', icon: CheckCircle, label: 'Completed' },
  cancelled: { color: 'text-red-400', bgColor: 'bg-red-500/20', icon: XCircle, label: 'Cancelled' }
};

/* ──────────────────────────────────────────────
   New Order Modal
   ────────────────────────────────────────────── */
function NewOrderModal({ open, onClose, onCreated }: { open: boolean; onClose: () => void; onCreated: () => void }) {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState('');
  const [lineItems, setLineItems] = useState<OrderLineItem[]>([{ productId: '', description: '', quantity: 1, unitPrice: 0 }]);
  const [notes, setNotes] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [loadingData, setLoadingData] = useState(true);

  useEffect(() => {
    if (!open) return;
    setLoadingData(true);
    Promise.all([
      fetch('/api/erp/crm/customers').then(r => r.json()),
      fetch('/api/erp/inventory?type=products').then(r => r.json()),
    ])
      .then(([custData, prodData]) => {
        setCustomers(custData.customers || []);
        setProducts(prodData.products || []);
      })
      .catch(() => setError('Failed to load customers/products'))
      .finally(() => setLoadingData(false));
  }, [open]);

  const addLine = () => setLineItems([...lineItems, { productId: '', description: '', quantity: 1, unitPrice: 0 }]);
  const removeLine = (i: number) => setLineItems(lineItems.filter((_, idx) => idx !== i));
  const updateLine = (i: number, patch: Partial<OrderLineItem>) => {
    setLineItems(lineItems.map((li, idx) => (idx === i ? { ...li, ...patch } : li)));
  };

  const handleProductSelect = (i: number, productId: string) => {
    const prod = products.find(p => p.id === productId);
    if (prod) {
      updateLine(i, { productId: prod.id, description: prod.name, unitPrice: prod.salePrice });
    } else {
      updateLine(i, { productId: '' });
    }
  };

  const subtotal = lineItems.reduce((s, li) => s + li.quantity * li.unitPrice, 0);
  const tax = Math.round(subtotal * 0.08 * 100) / 100;
  const total = Math.round((subtotal + tax) * 100) / 100;

  const handleSubmit = async () => {
    if (!selectedCustomer) { setError('Select a customer'); return; }
    const validItems = lineItems.filter(li => li.description && li.unitPrice > 0);
    if (validItems.length === 0) { setError('Add at least one valid line item'); return; }
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch('/api/erp/crm/sales-orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ customerId: selectedCustomer, items: validItems, notes }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to create order');
      onCreated();
      onClose();
      // Reset form
      setSelectedCustomer('');
      setLineItems([{ productId: '', description: '', quantity: 1, unitPrice: 0 }]);
      setNotes('');
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSubmitting(false);
    }
  };

  if (!open) return null;

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
        onClick={onClose}
      >
        <motion.div
          initial={{ scale: 0.95, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          exit={{ scale: 0.95, opacity: 0 }}
          onClick={(e) => e.stopPropagation()}
          className="w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-xl bg-[#0f1629] border border-sky-500/20 shadow-2xl"
        >
          {/* Modal Header */}
          <div className="flex items-center justify-between px-6 py-4 border-b border-sky-500/10">
            <h2 className="text-xl font-bold text-white flex items-center gap-2">
              <FileSpreadsheet className="w-5 h-5 text-green-400" />
              Create Sales Order
            </h2>
            <button onClick={onClose} className="p-1 rounded hover:bg-white/10 text-gray-400 hover:text-white">
              <X className="w-5 h-5" />
            </button>
          </div>

          {loadingData ? (
            <div className="flex items-center justify-center py-16">
              <Loader2 className="w-8 h-8 animate-spin text-sky-400" />
            </div>
          ) : (
            <div className="px-6 py-4 space-y-5">
              {/* Customer Select */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-1">Customer *</label>
                <select
                  value={selectedCustomer}
                  onChange={(e) => setSelectedCustomer(e.target.value)}
                  className="w-full px-3 py-2 bg-[#141b2d] border border-sky-500/20 rounded-lg text-white focus:ring-2 focus:ring-sky-500/50 focus:outline-none"
                >
                  <option value="">Select customer...</option>
                  {customers.map(c => (
                    <option key={c.id} value={c.id}>{c.customerNumber} — {c.name}</option>
                  ))}
                </select>
              </div>

              {/* Line Items */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Line Items *</label>
                <div className="space-y-2">
                  {lineItems.map((li, i) => (
                    <div key={i} className="flex gap-2 items-end">
                      {products.length > 0 ? (
                        <div className="flex-1">
                          <select
                            value={li.productId || ''}
                            onChange={(e) => handleProductSelect(i, e.target.value)}
                            className="w-full px-2 py-2 bg-[#141b2d] border border-sky-500/20 rounded-lg text-white text-sm focus:outline-none"
                          >
                            <option value="">— Select product or enter custom —</option>
                            {products.map(p => (
                              <option key={p.id} value={p.id}>{p.sku} — {p.name} (${p.salePrice})</option>
                            ))}
                          </select>
                        </div>
                      ) : null}
                      <input
                        type="text"
                        placeholder="Description"
                        value={li.description}
                        onChange={(e) => updateLine(i, { description: e.target.value })}
                        className="flex-1 px-2 py-2 bg-[#141b2d] border border-sky-500/20 rounded-lg text-white text-sm focus:outline-none"
                      />
                      <input
                        type="number"
                        min={1}
                        placeholder="Qty"
                        value={li.quantity}
                        onChange={(e) => updateLine(i, { quantity: Math.max(1, parseInt(e.target.value) || 1) })}
                        className="w-20 px-2 py-2 bg-[#141b2d] border border-sky-500/20 rounded-lg text-white text-sm focus:outline-none"
                      />
                      <input
                        type="number"
                        min={0}
                        step={0.01}
                        placeholder="Price"
                        value={li.unitPrice || ''}
                        onChange={(e) => updateLine(i, { unitPrice: parseFloat(e.target.value) || 0 })}
                        className="w-28 px-2 py-2 bg-[#141b2d] border border-sky-500/20 rounded-lg text-white text-sm focus:outline-none"
                      />
                      {lineItems.length > 1 && (
                        <button onClick={() => removeLine(i)} className="p-2 text-red-400 hover:text-red-300">
                          <Trash2 className="w-4 h-4" />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
                <button onClick={addLine} className="mt-2 text-sm text-sky-400 hover:text-sky-300 flex items-center gap-1">
                  <Plus className="w-3.5 h-3.5" /> Add line item
                </button>
              </div>

              {/* Totals */}
              <div className="bg-[#141b2d] rounded-lg p-3 space-y-1 border border-sky-500/10">
                <div className="flex justify-between text-sm text-gray-400">
                  <span>Subtotal</span>
                  <span className="text-white">${subtotal.toFixed(2)}</span>
                </div>
                <div className="flex justify-between text-sm text-gray-400">
                  <span>Tax (8%)</span>
                  <span className="text-white">${tax.toFixed(2)}</span>
                </div>
                <div className="flex justify-between text-base font-bold pt-1 border-t border-sky-500/10">
                  <span className="text-gray-300">Total</span>
                  <span className="text-green-400">${total.toFixed(2)}</span>
                </div>
              </div>

              {/* Notes */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-1">Notes</label>
                <textarea
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  rows={2}
                  className="w-full px-3 py-2 bg-[#141b2d] border border-sky-500/20 rounded-lg text-white text-sm focus:outline-none resize-none"
                  placeholder="Optional notes..."
                />
              </div>

              {error && <p className="text-red-400 text-sm">{error}</p>}

              {/* Actions */}
              <div className="flex justify-end gap-3 pt-2 border-t border-sky-500/10">
                <button onClick={onClose} className="px-4 py-2 text-gray-400 hover:text-white transition-colors">
                  Cancel
                </button>
                <button
                  onClick={handleSubmit}
                  disabled={submitting}
                  className="px-6 py-2 bg-green-600 hover:bg-green-700 disabled:opacity-50 text-white rounded-lg flex items-center gap-2 transition-colors"
                >
                  {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
                  {submitting ? 'Creating...' : 'Create Order'}
                </button>
              </div>
            </div>
          )}
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}

export default function SalesOrdersPage() {
  const [orders, setOrders] = useState<SalesOrder[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedOrder, setExpandedOrder] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [showNewOrder, setShowNewOrder] = useState(false);

  useEffect(() => {
    fetchOrders();
  }, [statusFilter]);

  const fetchOrders = async () => {
    try {
      const params = new URLSearchParams();
      if (statusFilter) params.set('status', statusFilter);
      const res = await fetch(`/api/erp/crm/sales-orders?${params}`);
      const data = await res.json();
      setOrders(data.orders || []);
    } catch (error) {
      console.error('Failed to fetch orders:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  // Calculate stats
  const totalRevenue = orders
    .filter(o => o.status === 'completed')
    .reduce((sum, o) => sum + (o.totalAmount || 0), 0);
  const pendingRevenue = orders
    .filter(o => !['completed', 'cancelled'].includes(o.status))
    .reduce((sum, o) => sum + (o.totalAmount || 0), 0);

  return (
    <div className="space-y-6">
      {/* New Order Modal */}
      <NewOrderModal
        open={showNewOrder}
        onClose={() => setShowNewOrder(false)}
        onCreated={fetchOrders}
      />

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

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="glass-card p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-green-500/10">
              <DollarSign className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Completed Revenue</p>
              <p className="text-xl font-bold text-white">{formatCurrency(totalRevenue)}</p>
            </div>
          </div>
        </div>
        <div className="glass-card p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-amber-500/10">
              <Clock className="w-5 h-5 text-amber-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Pending Revenue</p>
              <p className="text-xl font-bold text-white">{formatCurrency(pendingRevenue)}</p>
            </div>
          </div>
        </div>
        <div className="glass-card p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-blue-500/10">
              <Package className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Processing</p>
              <p className="text-xl font-bold text-white">
                {orders.filter(o => ['processing', 'confirmed'].includes(o.status)).length}
              </p>
            </div>
          </div>
        </div>
        <div className="glass-card p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-sky-500/10">
              <Truck className="w-5 h-5 text-sky-400" />
            </div>
            <div>
              <p className="text-gray-400 text-sm">Shipped</p>
              <p className="text-xl font-bold text-white">
                {orders.filter(o => o.status === 'shipped').length}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="flex gap-2 flex-wrap">
        {['', 'pending', 'confirmed', 'processing', 'shipped', 'completed'].map((status) => (
          <button
            key={status || 'all'}
            onClick={() => setStatusFilter(status)}
            className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
              statusFilter === status
                ? 'bg-green-600 text-white'
                : 'bg-brand-bg-elevated border border-brand-deep/30 text-gray-300 hover:text-white'
            }`}
          >
            {status ? statusConfig[status]?.label : 'All'}
          </button>
        ))}
      </div>

      {/* Orders List */}
      {loading ? (
        <div className="flex items-center justify-center h-64">
          <Loader2 className="w-8 h-8 animate-spin text-green-400" />
        </div>
      ) : orders.length === 0 ? (
        <div className="glass-card p-12 text-center">
          <FileSpreadsheet className="w-16 h-16 text-gray-600 mx-auto mb-4" />
          <h3 className="text-xl font-semibold text-white mb-2">No Sales Orders</h3>
          <p className="text-gray-400 mb-6">Orders will appear here when created from opportunities</p>
        </div>
      ) : (
        <div className="space-y-3">
          {orders.map((order, idx) => {
            const config = statusConfig[order.status] || statusConfig.pending;
            const isExpanded = expandedOrder === order.id;

            return (
              <motion.div
                key={order.id}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: idx * 0.03 }}
                className="glass-card overflow-hidden"
              >
                <div
                  className="p-4 flex items-center justify-between cursor-pointer hover:bg-brand-bg-elevated/50 transition-colors"
                  onClick={() => setExpandedOrder(isExpanded ? null : order.id)}
                >
                  <div className="flex items-center gap-4">
                    <div className={`p-2 rounded-lg ${config.bgColor}`}>
                      <config.icon className={`w-5 h-5 ${config.color}`} />
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="font-semibold text-white">{order.orderNumber}</h3>
                        <span className={`px-2 py-0.5 rounded text-xs ${config.color} ${config.bgColor}`}>
                          {config.label}
                        </span>
                      </div>
                      <p className="text-sm text-gray-400 flex items-center gap-2">
                        <Building2 className="w-3.5 h-3.5" />
                        {order.customer?.name || 'Unknown Customer'}
                        <span className="text-gray-600">|</span>
                        <Calendar className="w-3.5 h-3.5" />
                        {formatDate(order.createdAt)}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-4">
                    <div className="text-right">
                      <p className="text-lg font-bold text-white">
                        {formatCurrency(order.totalAmount || 0)}
                      </p>
                      <p className="text-xs text-gray-500">
                        {order.items?.length || 0} item{(order.items?.length || 0) !== 1 ? 's' : ''}
                      </p>
                    </div>
                    {isExpanded ? (
                      <ChevronDown className="w-5 h-5 text-gray-400" />
                    ) : (
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    )}
                  </div>
                </div>

                {isExpanded && order.items && order.items.length > 0 && (
                  <div className="border-t border-brand-deep/20 p-4 bg-brand-bg/50">
                    <h4 className="text-sm font-medium text-gray-300 mb-3">Order Items</h4>
                    <div className="space-y-2">
                      {order.items.map((item: any, i: number) => (
                        <div
                          key={i}
                          className="flex items-center justify-between p-2 bg-brand-bg-elevated/50 rounded-lg"
                        >
                          <div>
                            <p className="text-white">{item.product?.name || item.description || 'Item'}</p>
                            <p className="text-xs text-gray-500">
                              {item.quantity} × {formatCurrency(item.unitPrice || 0)}
                            </p>
                          </div>
                          <p className="text-white font-medium">
                            {formatCurrency(item.totalPrice || (item.quantity * item.unitPrice) || 0)}
                          </p>
                        </div>
                      ))}
                    </div>
                    <div className="mt-4 pt-3 border-t border-brand-deep/20 space-y-1">
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-400">Subtotal</span>
                        <span className="text-white">{formatCurrency(order.subtotal || 0)}</span>
                      </div>
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-400">Tax</span>
                        <span className="text-white">{formatCurrency(order.taxAmount || 0)}</span>
                      </div>
                      <div className="flex justify-between text-base font-bold pt-2">
                        <span className="text-gray-300">Total</span>
                        <span className="text-green-400">{formatCurrency(order.totalAmount || 0)}</span>
                      </div>
                    </div>
                  </div>
                )}
              </motion.div>
            );
          })}
        </div>
      )}
    </div>
  );
}
