'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 InventoryPage() {
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const [showAddForm, setShowAddForm] = useState(false);
  const [newProduct, setNewProduct] = useState({ name: '', type: 'steel', unit: 'kg', price: 0, cost_price: 0, stock_quantity: 0 });

  const [editingProduct, setEditingProduct] = useState<any>(null);

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

  const fetchProducts = async () => {
    try {
      const res = await fetch('/api/products');
      const data = await res.json();
      if(Array.isArray(data)) setProducts(data);
    } catch (e) {
      showToast('Failed to load products', 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleAddProduct = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newProduct)
      });
      if (res.ok) {
        showToast('Product added successfully', 'success');
        setShowAddForm(false);
        setNewProduct({ name: '', type: 'steel', unit: 'kg', price: 0, cost_price: 0, stock_quantity: 0 });
        fetchProducts();
      } else {
        showToast('Failed to add product', 'error');
      }
    } catch (e) {
      showToast('Failed to add product', 'error');
    }
  };

  const handleUpdateProduct = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch('/api/products', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editingProduct)
      });
      if (res.ok) {
        showToast('Product updated successfully', 'success');
        setEditingProduct(null);
        fetchProducts();
      } else {
        showToast('Failed to update product', 'error');
      }
    } catch (e) {
      showToast('Failed to update product', 'error');
    }
  };

  const columns = [
    { key: 'id', label: 'ID' },
    { key: 'name', label: 'Product Name' },
    { key: 'type', label: 'Type', render: (row: any) => <span style={{textTransform:'capitalize'}}>{row.type}</span> },
    { key: 'stock_quantity', label: 'Stock' },
    { key: 'unit', label: 'Unit', render: (row: any) => <span style={{textTransform:'capitalize'}}>{row.unit}</span> },
    { key: 'cost_price', label: 'Cost Price' },
    { key: 'price', label: 'Selling Price' },
    { key: 'actions', label: 'Actions', render: (row: any) => (
      <button onClick={() => setEditingProduct(row)} style={{ padding: '0.25rem 0.5rem', fontSize: '0.75rem' }}>Edit</button>
    )}
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
        <h1 style={{ margin: 0 }}>Inventory Management</h1>
        <button className="primary" onClick={() => setShowAddForm(!showAddForm)}>
          <Plus size={18} /> Add New Product
        </button>
      </div>

      {showAddForm && (
        <div className="panel" style={{ marginBottom: '1.5rem', animation: 'slideIn 0.2s ease' }}>
          <h3 style={{ marginBottom: '1rem' }}>Add New Product</h3>
          <form onSubmit={handleAddProduct} className="grid grid-4" style={{ alignItems: 'end' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Product Name</label>
              <input type="text" required value={newProduct.name} onChange={e => setNewProduct({...newProduct, name: e.target.value})} />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Type</label>
              <select value={newProduct.type} onChange={e => setNewProduct({...newProduct, type: e.target.value})}>
                <option value="steel">Steel</option>
                <option value="cement">Cement</option>
              </select>
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Unit</label>
              <select value={newProduct.unit} onChange={e => setNewProduct({...newProduct, unit: e.target.value})}>
                <option value="kg">Kg</option>
                <option value="bag">Bag</option>
              </select>
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Cost Price (Buying)</label>
              <input type="number" step="0.01" required value={Number.isNaN(newProduct.cost_price) ? '' : newProduct.cost_price} onChange={e => setNewProduct({...newProduct, cost_price: parseFloat(e.target.value)})} />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Selling Price</label>
              <input type="number" step="0.01" required value={Number.isNaN(newProduct.price) ? '' : newProduct.price} onChange={e => setNewProduct({...newProduct, price: parseFloat(e.target.value)})} />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Initial Stock</label>
              <input type="number" step="0.01" required value={Number.isNaN(newProduct.stock_quantity) ? '' : newProduct.stock_quantity} onChange={e => setNewProduct({...newProduct, stock_quantity: parseFloat(e.target.value)})} />
            </div>
            <div style={{ gridColumn: 'span 2' }}>
              <button type="submit" className="primary" style={{ width: '100%', height: '42px' }}>Save Product</button>
            </div>
          </form>
        </div>
      )}

      {editingProduct && (
        <div className="panel" style={{ marginBottom: '1.5rem', animation: 'slideIn 0.2s ease', border: '2px solid var(--accent)' }}>
          <h3 style={{ marginBottom: '1rem' }}>Edit Product</h3>
          <form onSubmit={handleUpdateProduct} className="grid grid-4" style={{ alignItems: 'end' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Product Name</label>
              <input type="text" required value={editingProduct.name} onChange={e => setEditingProduct({...editingProduct, name: e.target.value})} />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Type</label>
              <select value={editingProduct.type} onChange={e => setEditingProduct({...editingProduct, type: e.target.value})}>
                <option value="steel">Steel</option>
                <option value="cement">Cement</option>
              </select>
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Unit</label>
              <select value={editingProduct.unit} onChange={e => setEditingProduct({...editingProduct, unit: e.target.value})}>
                <option value="kg">Kg</option>
                <option value="bag">Bag</option>
              </select>
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Cost Price (Buying)</label>
              <input type="number" step="0.01" required value={Number.isNaN(editingProduct.cost_price) ? '' : editingProduct.cost_price} onChange={e => setEditingProduct({...editingProduct, cost_price: parseFloat(e.target.value)})} />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Selling Price</label>
              <input type="number" step="0.01" required value={Number.isNaN(editingProduct.price) ? '' : editingProduct.price} onChange={e => setEditingProduct({...editingProduct, price: parseFloat(e.target.value)})} />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', color: 'var(--text-muted)' }}>Current Stock</label>
              <input type="number" step="0.01" required value={Number.isNaN(editingProduct.stock_quantity) ? '' : editingProduct.stock_quantity} onChange={e => setEditingProduct({...editingProduct, stock_quantity: parseFloat(e.target.value)})} />
            </div>
            <div style={{ gridColumn: 'span 2', display: 'flex', gap: '1rem' }}>
              <button type="submit" className="primary" style={{ flex: 1, height: '42px' }}>Update Product</button>
              <button type="button" onClick={() => setEditingProduct(null)} style={{ flex: 1, height: '42px' }}>Cancel</button>
            </div>
          </form>
        </div>
      )}

      <div className="panel">
        {loading ? <p>Loading products from database...</p> : <DataTable columns={columns} data={products} />}
      </div>
    </div>
  );
}
