import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

function Stock() {
  const [mode, setMode] = useState('in');
  const [spareParts, setSpareParts] = useState([]);
  const [stockInRecords, setStockInRecords] = useState([]);
  const [stockOutRecords, setStockOutRecords] = useState([]);
  const [selectedPart, setSelectedPart] = useState('');
  const [date, setDate] = useState(new Date().toISOString().slice(0, 10));
  const [quantity, setQuantity] = useState('');
  const [unitCost, setUnitCost] = useState('');
  const [reason, setReason] = useState('Sale');
  const [destination, setDestination] = useState('');
  const [notes, setNotes] = useState('');
  const [message, setMessage] = useState('');

  const headers = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  };

  const clearForm = () => {
    setSelectedPart('');
    setQuantity('');
    setUnitCost('');
    setReason('Sale');
    setDestination('');
    setNotes('');
    setMessage('');
  };

  const loadSpareParts = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/spareparts/list', { headers });
      setSpareParts(res.data);
    } catch (err) {
      console.log(err);
    }
  };

  const loadStock = async () => {
    try {
      const [ins, outs] = await Promise.all([
        axios.get('http://localhost:5001/api/stock/in', { headers }),
        axios.get('http://localhost:5001/api/stock/out', { headers }),
      ]);
      setStockInRecords(ins.data);
      setStockOutRecords(outs.data);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    loadSpareParts();
    loadStock();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!selectedPart) {
      setMessage('Select a spare part first');
      return;
    }

    try {
      if (mode === 'in') {
        await axios.post(
          'http://localhost:5001/api/stock/in',
          { date, quantity, unitCost, notes, sparePart: selectedPart },
          { headers }
        );
        setMessage('Stock in recorded');
      } else {
        await axios.post(
          'http://localhost:5001/api/stock/out',
          { date, quantity, reason, destination, sparePart: selectedPart },
          { headers }
        );
        setMessage('Stock out recorded');
      }

      clearForm();
      loadSpareParts();
      loadStock();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to save stock record');
      console.log(err);
    }
  };

  return (
    <div className="max-w-3xl mx-auto p-4">
      <div className="mt-3 mb-6">
        <Link
          to="/dashboard"
          type="button"
          className="font-medium hover:text-white border border-slate-600 rounded-lg px-3 py-2 hover:bg-slate-800 transition-colors"
        >
          BACK
        </Link>
      </div>

      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 className="text-2xl font-bold">Stock Management</h1>
        <div className="flex gap-2">
          <button
            type="button"
            className={`rounded-lg px-4 py-2 ${mode === 'in' ? 'bg-slate-900 text-white' : 'border border-slate-300 text-slate-700'}`}
            onClick={() => setMode('in')}
          >
            Stock In
          </button>
          <button
            type="button"
            className={`rounded-lg px-4 py-2 ${mode === 'out' ? 'bg-slate-900 text-white' : 'border border-slate-300 text-slate-700'}`}
            onClick={() => setMode('out')}
          >
            Stock Out
          </button>
        </div>
      </div>

      {message && <p className="mb-4 text-green-600">{message}</p>}

      <form onSubmit={handleSubmit} className="border p-4 rounded space-y-4">
        <div className="space-y-2">
          <label className="block text-sm font-medium text-slate-700">Spare Part</label>
          <select
            value={selectedPart}
            onChange={(e) => setSelectedPart(e.target.value)}
            className="w-full border p-2 rounded"
            required
          >
            <option value="">Select a spare part</option>
            {spareParts.map((part) => (
              <option key={part._id} value={part._id}>
                {part.partCode} — {part.partName}
              </option>
            ))}
          </select>
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <label className="block text-sm font-medium text-slate-700">Date</label>
            <input
              type="date"
              value={date}
              onChange={(e) => setDate(e.target.value)}
              className="w-full border p-2 rounded"
              required
            />
          </div>

          <div className="space-y-2">
            <label className="block text-sm font-medium text-slate-700">Quantity</label>
            <input
              type="number"
              value={quantity}
              onChange={(e) => setQuantity(e.target.value)}
              className="w-full border p-2 rounded"
              required
            />
          </div>
        </div>

        {mode === 'in' ? (
          <>
            <div className="space-y-2">
              <label className="block text-sm font-medium text-slate-700">Unit Cost</label>
              <input
                type="text"
                value={unitCost}
                onChange={(e) => setUnitCost(e.target.value)}
                className="w-full border p-2 rounded"
                required
              />
            </div>
            <div className="space-y-2">
              <label className="block text-sm font-medium text-slate-700">Notes</label>
              <input
                type="text"
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                className="w-full border p-2 rounded"
                placeholder="Supplier or batch info"
              />
            </div>
          </>
        ) : (
          <>
            <div className="space-y-2">
              <label className="block text-sm font-medium text-slate-700">Reason</label>
              <input
                type="text"
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                className="w-full border p-2 rounded"
                required
              />
            </div>
            <div className="space-y-2">
              <label className="block text-sm font-medium text-slate-700">Destination</label>
              <input
                type="text"
                value={destination}
                onChange={(e) => setDestination(e.target.value)}
                className="w-full border p-2 rounded"
                placeholder="Customer, department, etc."
              />
            </div>
          </>
        )}

        <button type="submit" className="bg-blue-500 text-white px-4 py-2 rounded">
          {mode === 'in' ? 'Record Stock In' : 'Record Stock Out'}
        </button>
      </form>

      <div className="mt-8 space-y-4">
        <section>
          <h2 className="text-xl font-semibold mb-3">Recent Stock In</h2>
          {stockInRecords.length === 0 ? (
            <p className="text-slate-600">No stock in records yet.</p>
          ) : (
            stockInRecords.map((item) => (
              <div key={item._id} className="border p-3 rounded mb-3">
                <p>Part: {item.sparePart?.partName || 'Unknown'}</p>
                <p>Date: {new Date(item.date).toLocaleDateString()}</p>
                <p>Quantity: {item.quantity}</p>
                <p>Unit Cost: {item.unitCost}</p>
                <p>Notes: {item.notes || '—'}</p>
              </div>
            ))
          )}
        </section>

        <section>
          <h2 className="text-xl font-semibold mb-3">Recent Stock Out</h2>
          {stockOutRecords.length === 0 ? (
            <p className="text-slate-600">No stock out records yet.</p>
          ) : (
            stockOutRecords.map((item) => (
              <div key={item._id} className="border p-3 rounded mb-3">
                <p>Part: {item.sparePart?.partName || 'Unknown'}</p>
                <p>Date: {new Date(item.date).toLocaleDateString()}</p>
                <p>Quantity: {item.quantity}</p>
                <p>Reason: {item.reason}</p>
                <p>Destination: {item.destination || '—'}</p>
              </div>
            ))
          )}
        </section>
      </div>
    </div>
  );
}

export default Stock;
