'use client';

import React, { useEffect, useState } from 'react';
import DataTable from '@/components/DataTable';
import { showToast } from '@/components/toast';
import { Plus } from 'lucide-react';

export default function SuppliersPage() {
  const [suppliers, setSuppliers] = useState<any[]>([]);
  const [products, setProducts] = useState<any[]>([]);
  
  const [showAddSupplier, setShowAddSupplier] = useState(false);
  const [newSupplier, setNewSupplier] = useState({ name: '', contact_info: '' });
  
  const [showPurchaseForm, setShowPurchaseForm] = useState(false);
  const [purchaseData, setPurchaseData] = useState({ supplier_id: '', items: [] as any[] });
  
  // temporary item to add to purchase
  const [tempItem, setTempItem] = useState({ product_id: '', quantity: 0, unit_price: 0 });

  useEffect(() => {
    fetchSuppliers();
    fetchProducts();
  }, []);

  const fetchSuppliers = async () => {
    const res = await fetch('/api/suppliers');
    const data = await res.json();
    if (Array.isArray(data)) setSuppliers(data);
  };
  
  const fetchProducts = async () => {
    const res = await fetch('/api/products');
    const data = await res.json();
    if (Array.isArray(data)) setProducts(data);
  };

  const handleAddSupplier = async (e: React.FormEvent) => {
    e.preventDefault();
    const res = await fetch('/api/suppliers', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(newSupplier)
    });
    if (res.ok) {
      showToast('Supplier Added', 'success');
      setNewSupplier({ name: '', contact_info: '' });
      setShowAddSupplier(false);
      fetchSuppliers();
    } else {
      showToast('Error adding supplier', 'error');
    }
  };

  const handleAddPurchaseItem = (e: React.FormEvent) => {
    e.preventDefault();
    if (!tempItem.product_id || tempItem.quantity <= 0 || tempItem.unit_price <= 0) {
      showToast('Please fill all item fields correctly', 'error');
      return;
    }
    const product = products.find(p => p.id.toString() === tempItem.product_id);
    if (!product) return;
    
    setPurchaseData(prev => ({
      ...prev,
      items: [...prev.items, { ...tempItem, product_name: product.name, unit: product.unit }]
    }));
    
    setTempItem({ product_id: '', quantity: 0, unit_price: 0 });
  };

  const submitPurchase = async () => {
    if (!purchaseData.supplier_id) return showToast('Please select a supplier', 'error');
    if (purchaseData.items.length === 0) return showToast('Please add items to purchase', 'error');

    const total_amount = purchaseData.items.reduce((sum, item) => sum + (item.quantity * item.unit_price), 0);
    
    const payload = {
      supplier_id: parseInt(purchaseData.supplier_id),
      total_amount,
      items: purchaseData.items.map(i => ({ product_id: parseInt(i.product_id), quantity: i.quantity, unit_price: i.unit_price }))
    };

    const res = await fetch('/api/purchases', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });
    
    if (res.ok) {
      showToast('Purchase recorded successfully! Stock has been updated.', 'success');
      setShowPurchaseForm(false);
      setPurchaseData({ supplier_id: '', items: [] });
      fetchProducts(); // Refresh products if needed
    } else {
      showToast('Error recording purchase', 'error');
    }
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
        <h1 style={{ margin: 0 }}>Suppliers & Purchases</h1>
        <div style={{ display: 'flex', gap: '1rem' }}>
          <button className="primary" onClick={() => setShowPurchaseForm(!showPurchaseForm)}>
            <Plus size={18} /> New Purchase (Add Stock)
          </button>
          <button onClick={() => setShowAddSupplier(!showAddSupplier)}>
            <Plus size={18} /> Add Supplier
          </button>
        </div>
      </div>

      {showAddSupplier && (
        <div className="panel" style={{ marginBottom: '1.5rem', animation: 'slideIn 0.2s ease' }}>
          <h3 style={{ marginBottom: '1rem' }}>Add New Supplier</h3>
          <form onSubmit={handleAddSupplier} className="grid grid-3" style={{ alignItems: 'end' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Company / Supplier Name</label>
              <input type="text" required value={newSupplier.name} onChange={e => setNewSupplier({...newSupplier, name: e.target.value})} />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Contact Info</label>
              <input type="text" required value={newSupplier.contact_info} onChange={e => setNewSupplier({...newSupplier, contact_info: e.target.value})} />
            </div>
            <div>
              <button type="submit" className="primary" style={{ width: '100%', height: '42px' }}>Save Supplier</button>
            </div>
          </form>
        </div>
      )}

      {showPurchaseForm && (
        <div className="panel" style={{ marginBottom: '1.5rem', animation: 'slideIn 0.2s ease', border: '2px solid var(--accent)' }}>
          <h3 style={{ marginBottom: '1rem' }}>Record Purchase (This will increase product stock)</h3>
          
          <div style={{ marginBottom: '1.5rem' }}>
            <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Select Supplier</label>
            <select value={purchaseData.supplier_id} onChange={e => setPurchaseData({...purchaseData, supplier_id: e.target.value})} style={{ width: '300px' }}>
              <option value="">-- Choose Supplier --</option>
              {suppliers.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
            </select>
          </div>
          
          <div style={{ borderTop: '1px solid var(--panel-border)', paddingTop: '1rem', marginBottom: '1rem' }}>
            <h4 style={{ marginBottom: '1rem' }}>Add Items to Purchase</h4>
            <form onSubmit={handleAddPurchaseItem} className="grid grid-4" style={{ alignItems: 'end' }}>
              <div>
                <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Product</label>
                <select value={tempItem.product_id} onChange={e => {
                  const pid = e.target.value;
                  const prod = products.find(p => p.id.toString() === pid);
                  setTempItem({...tempItem, product_id: pid, unit_price: prod ? parseFloat(prod.cost_price) : 0});
                }}>
                  <option value="">-- Select Product --</option>
                  {products.map(p => <option key={p.id} value={p.id}>{p.name} ({p.unit})</option>)}
                </select>
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Quantity</label>
                <input type="number" step="0.01" value={Number.isNaN(tempItem.quantity) ? '' : tempItem.quantity} onChange={e => setTempItem({...tempItem, quantity: parseFloat(e.target.value)})} />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Unit Price (Cost)</label>
                <input type="number" step="0.01" value={Number.isNaN(tempItem.unit_price) ? '' : tempItem.unit_price} onChange={e => setTempItem({...tempItem, unit_price: parseFloat(e.target.value)})} />
              </div>
              <div>
                <button type="submit" style={{ width: '100%', height: '42px', background: 'var(--bg-color)' }}>Add to List</button>
              </div>
            </form>
          </div>

          {purchaseData.items.length > 0 && (
            <div style={{ marginTop: '1.5rem' }}>
              <h4>Purchase List</h4>
              <table className="data-table" style={{ marginBottom: '1rem' }}>
                <thead><tr><th>Product</th><th>Qty</th><th>Unit Price</th><th>Total</th></tr></thead>
                <tbody>
                  {purchaseData.items.map((item, idx) => (
                    <tr key={idx}>
                      <td>{item.product_name}</td>
                      <td>{item.quantity} {item.unit}</td>
                      <td>Rs {item.unit_price}</td>
                      <td>Rs {item.quantity * item.unit_price}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <div style={{ textAlign: 'right' }}>
                <strong style={{ fontSize: '1.2rem', marginRight: '1rem' }}>Total Amount: Rs {purchaseData.items.reduce((sum, item) => sum + (item.quantity * item.unit_price), 0)}</strong>
                <button className="primary" onClick={submitPurchase}>Complete Purchase & Update Stock</button>
              </div>
            </div>
          )}
        </div>
      )}

      <div className="panel">
        <h3 style={{ marginBottom: '1rem' }}>Existing Suppliers</h3>
        <DataTable 
          columns={[{ key: 'id', label: 'ID' }, { key: 'name', label: 'Supplier Name' }, { key: 'contact_info', label: 'Contact Info' }]} 
          data={suppliers} 
        />
      </div>
    </div>
  );
}
