'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  ShoppingCart, Plus, Package, Truck, Check,
  Loader2, Search, Calendar, DollarSign, Clock
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface PurchaseOrder {
  id: string;
  orderNumber: string;
  orderDate: string;
  expectedDate?: string;
  status: string;
  total: number;
  supplier?: { name: string };
  items?: Array<{
    quantity: number;
    unitPrice: number;
    product?: { name: string; sku: string };
  }>;
}

interface Supplier {
  id: string;
  name: string;
  code: string;
}

interface Product {
  id: string;
  sku: string;
  name: string;
  costPrice: number;
}

export default function OrdersPage() {
  const [orders, setOrders] = useState<PurchaseOrder[]>([]);
  const [suppliers, setSuppliers] = useState<Supplier[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [formData, setFormData] = useState({
    supplierId: '',
    expectedDate: '',
    items: [{ productId: '', quantity: '1', unitPrice: '' }],
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const [ordRes, supRes, prodRes] = await Promise.all([
        fetch('/api/erp/inventory?type=purchase-orders'),
        fetch('/api/erp/inventory?type=suppliers'),
        fetch('/api/erp/inventory?type=products'),
      ]);
      const ordData = await ordRes.json();
      const supData = await supRes.json();
      const prodData = await prodRes.json();
      setOrders(ordData.purchaseOrders || []);
      setSuppliers(supData.suppliers || []);
      setProducts(prodData.products || []);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const handleAddItem = () => {
    setFormData({
      ...formData,
      items: [...formData.items, { productId: '', quantity: '1', unitPrice: '' }],
    });
  };

  const handleRemoveItem = (index: number) => {
    setFormData({
      ...formData,
      items: formData.items.filter((_, i) => i !== index),
    });
  };

  const handleItemChange = (index: number, field: string, value: string) => {
    const newItems = [...formData.items];
    newItems[index] = { ...newItems[index], [field]: value };
    
    // Auto-fill unit price when product is selected
    if (field === 'productId' && value) {
      const product = products.find(p => p.id === value);
      if (product) {
        newItems[index].unitPrice = product.costPrice.toString();
      }
    }
    
    setFormData({ ...formData, items: newItems });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.supplierId || formData.items.length === 0) return;

    const validItems = formData.items.filter(item => item.productId && item.quantity && item.unitPrice);
    if (validItems.length === 0) return;

    setSubmitting(true);
    try {
      const items = validItems.map(item => ({
        productId: item.productId,
        quantity: parseInt(item.quantity),
        unitPrice: parseFloat(item.unitPrice),
        total: parseInt(item.quantity) * parseFloat(item.unitPrice),
      }));

      const total = items.reduce((sum, item) => sum + item.total, 0);

      const res = await fetch('/api/erp/inventory', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'purchase-order',
          data: {
            orderNumber: `PO-${Date.now().toString().slice(-8)}`,
            supplierId: formData.supplierId,
            orderDate: new Date(),
            expectedDate: formData.expectedDate ? new Date(formData.expectedDate) : null,
            status: 'draft',
            total,
            items,
          },
        }),
      });
      if (res.ok) {
        setShowModal(false);
        setFormData({
          supplierId: '',
          expectedDate: '',
          items: [{ productId: '', quantity: '1', unitPrice: '' }],
        });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to create order:', error);
    } finally {
      setSubmitting(false);
    }
  };

  const handleStatusUpdate = async (orderId: string, newStatus: string) => {
    try {
      const res = await fetch('/api/erp/inventory', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'purchase-order',
          id: orderId,
          data: { status: newStatus },
        }),
      });
      if (res.ok) {
        fetchData();
      }
    } catch (error) {
      console.error('Failed to update order:', error);
    }
  };

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

  const formatDate = (dateStr: string) => {
    if (!dateStr) return 'N/A';
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'draft': return 'bg-gray-500/10 text-gray-400';
      case 'sent': return 'bg-blue-500/10 text-blue-400';
      case 'confirmed': return 'bg-brand-deep/10 text-brand';
      case 'received': return 'bg-green-500/10 text-green-400';
      case 'cancelled': return 'bg-red-500/10 text-red-400';
      default: return 'bg-gray-500/10 text-gray-400';
    }
  };

  const filteredOrders = orders.filter(order => {
    const matchesSearch = (order.orderNumber?.toLowerCase() || '').includes(searchTerm.toLowerCase()) ||
                          (order.supplier?.name?.toLowerCase() || '').includes(searchTerm.toLowerCase());
    const matchesFilter = filterStatus === 'all' || order.status === filterStatus;
    return matchesSearch && matchesFilter;
  });

  const totalValue = orders.reduce((sum, o) => sum + (o.total || 0), 0);
  const pendingCount = orders.filter(o => ['draft', 'sent', 'confirmed'].includes(o.status)).length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <ShoppingCart className="w-7 h-7 text-brand" />
            Purchase Orders
          </h1>
          <p className="text-gray-400 mt-1">Manage supplier orders</p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="flex items-center gap-2 px-4 py-2 bg-brand-deep hover:bg-brand-deep text-white rounded-lg transition-colors"
        >
          <Plus className="w-4 h-4" />
          New Order
        </button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <p className="text-sm text-gray-400">Total Orders</p>
          <p className="text-xl font-bold text-white">{orders.length}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-yellow-400" />
            <p className="text-sm text-gray-400">Pending</p>
          </div>
          <p className="text-xl font-bold text-yellow-400">{pendingCount}</p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <Check className="w-4 h-4 text-green-400" />
            <p className="text-sm text-gray-400">Received</p>
          </div>
          <p className="text-xl font-bold text-green-400">
            {orders.filter(o => o.status === 'received').length}
          </p>
        </div>
        <div className="p-4 bg-white/5 border border-white/10 rounded-lg">
          <div className="flex items-center gap-2">
            <DollarSign className="w-4 h-4 text-brand" />
            <p className="text-sm text-gray-400">Total Value</p>
          </div>
          <p className="text-xl font-bold text-brand">{formatCurrency(totalValue)}</p>
        </div>
      </div>

      {/* Filters */}
      <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-4 h-4 text-gray-500" />
          <input
            type="text"
            placeholder="Search orders..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-white/5 border border-white/10 rounded-lg text-white placeholder-gray-500 focus:border-brand-deep focus:outline-none"
          />
        </div>
        <div className="flex gap-2 overflow-x-auto pb-2">
          {['all', 'draft', 'sent', 'confirmed', 'received', 'cancelled'].map((status) => (
            <button
              key={status}
              onClick={() => setFilterStatus(status)}
              className={`px-3 py-2 rounded-lg text-sm capitalize whitespace-nowrap transition-colors ${
                filterStatus === status
                  ? 'bg-brand-deep text-white'
                  : 'bg-white/5 text-gray-400 hover:bg-white/10'
              }`}
            >
              {status}
            </button>
          ))}
        </div>
      </div>

      {/* Orders List */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      ) : (
        <div className="space-y-4">
          {filteredOrders.length === 0 ? (
            <div className="text-center py-12 text-gray-500 bg-white/5 border border-white/10 rounded-lg">
              No orders found
            </div>
          ) : (
            filteredOrders.map((order, index) => (
              <motion.div
                key={order.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.03 }}
                className="p-4 bg-white/5 border border-white/10 rounded-lg"
              >
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-4">
                    <div className="p-2 bg-brand-deep/10 rounded-lg">
                      <ShoppingCart className="w-5 h-5 text-brand" />
                    </div>
                    <div>
                      <h3 className="font-semibold text-white">{order.orderNumber}</h3>
                      <p className="text-sm text-gray-400">{order.supplier?.name || 'Unknown Supplier'}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className={`text-xs px-2 py-1 rounded capitalize ${getStatusColor(order.status)}`}>
                      {order.status}
                    </span>
                    <span className="text-lg font-bold text-white">{formatCurrency(order.total)}</span>
                  </div>
                </div>
                <div className="flex items-center justify-between text-sm">
                  <div className="flex items-center gap-4 text-gray-500">
                    <span className="flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      Ordered: {formatDate(order.orderDate)}
                    </span>
                    {order.expectedDate && (
                      <span className="flex items-center gap-1">
                        <Truck className="w-3 h-3" />
                        Expected: {formatDate(order.expectedDate)}
                      </span>
                    )}
                    <span className="flex items-center gap-1">
                      <Package className="w-3 h-3" />
                      {order.items?.length || 0} items
                    </span>
                  </div>
                  {order.status !== 'received' && order.status !== 'cancelled' && (
                    <div className="flex gap-2">
                      {order.status === 'draft' && (
                        <button
                          onClick={() => handleStatusUpdate(order.id, 'sent')}
                          className="px-3 py-1 bg-blue-500/10 hover:bg-blue-500/20 text-blue-400 rounded text-xs transition-colors"
                        >
                          Send
                        </button>
                      )}
                      {order.status === 'sent' && (
                        <button
                          onClick={() => handleStatusUpdate(order.id, 'confirmed')}
                          className="px-3 py-1 bg-brand-deep/10 hover:bg-brand-deep/20 text-brand rounded text-xs transition-colors"
                        >
                          Confirm
                        </button>
                      )}
                      {order.status === 'confirmed' && (
                        <button
                          onClick={() => handleStatusUpdate(order.id, 'received')}
                          className="px-3 py-1 bg-green-500/10 hover:bg-green-500/20 text-green-400 rounded text-xs transition-colors"
                        >
                          Mark Received
                        </button>
                      )}
                    </div>
                  )}
                </div>
              </motion.div>
            ))
          )}
        </div>
      )}

      {/* New Order Modal */}
      <ERPModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        title="Create Purchase Order"
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-400 mb-1">Supplier</label>
              <select
                value={formData.supplierId}
                onChange={(e) => setFormData({ ...formData, supplierId: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
                required
              >
                <option value="">Select supplier...</option>
                {suppliers.map((sup) => (
                  <option key={sup.id} value={sup.id}>
                    {sup.name}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm text-gray-400 mb-1">Expected Delivery</label>
              <input
                type="date"
                value={formData.expectedDate}
                onChange={(e) => setFormData({ ...formData, expectedDate: e.target.value })}
                className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep focus:outline-none"
              />
            </div>
          </div>

          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="block text-sm text-gray-400">Order Items</label>
              <button
                type="button"
                onClick={handleAddItem}
                className="text-xs text-brand hover:text-brand-light"
              >
                + Add Item
              </button>
            </div>
            <div className="space-y-2 max-h-48 overflow-y-auto">
              {formData.items.map((item, index) => (
                <div key={index} className="grid grid-cols-12 gap-2">
                  <select
                    value={item.productId}
                    onChange={(e) => handleItemChange(index, 'productId', e.target.value)}
                    className="col-span-5 px-2 py-1 bg-white/5 border border-white/10 rounded text-white text-sm focus:border-brand-deep focus:outline-none"
                  >
                    <option value="">Select product...</option>
                    {products.map((prod) => (
                      <option key={prod.id} value={prod.id}>
                        {prod.sku} - {prod.name}
                      </option>
                    ))}
                  </select>
                  <input
                    type="number"
                    placeholder="Qty"
                    value={item.quantity}
                    onChange={(e) => handleItemChange(index, 'quantity', e.target.value)}
                    className="col-span-2 px-2 py-1 bg-white/5 border border-white/10 rounded text-white text-sm focus:border-brand-deep focus:outline-none"
                    min="1"
                  />
                  <input
                    type="number"
                    placeholder="Price"
                    step="0.01"
                    value={item.unitPrice}
                    onChange={(e) => handleItemChange(index, 'unitPrice', e.target.value)}
                    className="col-span-3 px-2 py-1 bg-white/5 border border-white/10 rounded text-white text-sm focus:border-brand-deep focus:outline-none"
                  />
                  <button
                    type="button"
                    onClick={() => handleRemoveItem(index)}
                    className="col-span-2 px-2 py-1 bg-red-500/10 hover:bg-red-500/20 text-red-400 rounded text-xs"
                    disabled={formData.items.length === 1}
                  >
                    Remove
                  </button>
                </div>
              ))}
            </div>
          </div>

          <div className="p-3 bg-white/5 rounded-lg">
            <div className="flex justify-between text-sm">
              <span className="text-gray-400">Total:</span>
              <span className="font-bold text-white">
                {formatCurrency(
                  formData.items.reduce(
                    (sum, item) => sum + (parseFloat(item.quantity) || 0) * (parseFloat(item.unitPrice) || 0),
                    0
                  )
                )}
              </span>
            </div>
          </div>

          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={() => setShowModal(false)}
              className="px-4 py-2 text-gray-400 hover:text-white transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting || !formData.supplierId || formData.items.every(i => !i.productId)}
              className="px-4 py-2 bg-brand-deep hover:bg-brand-deep disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-colors flex items-center gap-2"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              Create Order
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
