import { useState } from 'react';
import { useEquipmentStore } from '@/stores/equipmentStore';
import { useUIStore } from '@/stores/uiStore';
import { format } from 'date-fns';
import { Loader2, X, ShoppingCart } from 'lucide-react';

export default function RecordBuyScreen() {
  const { items, recordBuy } = useEquipmentStore();
  const { goBack, showToast } = useUIStore();
  const [equipmentId, setEquipmentId] = useState<number | ''>('');
  const [quantity, setQuantity] = useState(1);
  const [unitCost, setUnitCost] = useState('');
  const [supplier, setSupplier] = useState('');
  const [purchaseDate, setPurchaseDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [notes, setNotes] = useState('');
  const [isSaving, setIsSaving] = useState(false);

  const selectedItem = items.find(i => i.id === Number(equipmentId));
  const totalCost = (Number(unitCost) || 0) * quantity;

  const handleSubmit = async () => {
    if (!equipmentId || !unitCost || quantity < 1) {
      showToast({ type: 'error', message: 'Fill all required fields' });
      return;
    }
    setIsSaving(true);
    await recordBuy({
      equipmentId: Number(equipmentId),
      quantity,
      unitCost: parseFloat(unitCost),
      supplier: supplier || undefined,
      purchaseDate,
      notes: notes || undefined,
    });
    setIsSaving(false);
    showToast({ type: 'success', message: `Purchased ${quantity} units of ${selectedItem?.name} for Rs.${totalCost}` });
    goBack();
  };

  const inputClass = "w-full h-11 px-3 bg-white border border-gray-200 rounded-xl text-sm text-gray-900 focus:outline-none focus:border-orange-500 focus:ring-2 focus:ring-orange-500/15 transition-all";
  const labelClass = "block text-xs font-semibold text-gray-500 mb-1.5 uppercase tracking-wide";

  return (
    <div className="px-4 pt-4 pb-4">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 bg-blue-50 rounded-lg flex items-center justify-center">
            <ShoppingCart className="w-4 h-4 text-blue-500" />
          </div>
          <h2 className="text-lg font-bold text-gray-900">Record Purchase</h2>
        </div>
        <button onClick={goBack} className="p-2 -mr-2"><X className="w-5 h-5 text-gray-500" /></button>
      </div>

      <div className="space-y-4">
        <div>
          <label className={labelClass}>Equipment *</label>
          <select value={equipmentId} onChange={e => {
            const id = Number(e.target.value);
            setEquipmentId(id);
            const item = items.find(i => i.id === id);
            if (item) setUnitCost(item.unitCost.toString());
          }} className={inputClass}>
            <option value="">Select equipment...</option>
            {items.map(i => <option key={i.id} value={i.id}>{i.name} (Stock: {i.currentStock})</option>)}
          </select>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Quantity *</label>
            <input type="number" min={1} value={quantity} onChange={e => setQuantity(parseInt(e.target.value) || 1)} className={inputClass} />
          </div>
          <div>
            <label className={labelClass}>Unit Cost (Rs.) *</label>
            <input type="number" value={unitCost} onChange={e => setUnitCost(e.target.value)} placeholder="0.00" className={inputClass} />
          </div>
        </div>

        {totalCost > 0 && (
          <div className="bg-blue-50 border border-blue-100 rounded-xl p-3">
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">Total Cost</span>
              <span className="font-bold text-blue-700">Rs.{totalCost.toLocaleString('en-IN')}</span>
            </div>
          </div>
        )}

        <div>
          <label className={labelClass}>Supplier</label>
          <input type="text" value={supplier} onChange={e => setSupplier(e.target.value)} placeholder="e.g. SkatePro Suppliers" className={inputClass} />
        </div>

        <div>
          <label className={labelClass}>Purchase Date</label>
          <input type="date" value={purchaseDate} onChange={e => setPurchaseDate(e.target.value)} className={inputClass} />
        </div>

        <div>
          <label className={labelClass}>Notes</label>
          <textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder="Optional" className="w-full h-20 px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500 resize-none" />
        </div>

        <button onClick={handleSubmit} disabled={isSaving}
          className="w-full h-12 bg-blue-500 text-white font-semibold rounded-xl shadow-lg shadow-blue-500/30 flex items-center justify-center gap-2 disabled:opacity-50 active:scale-[0.98] transition-transform">
          {isSaving ? <Loader2 className="w-5 h-5 animate-spin" /> : `Record Purchase`}
        </button>
      </div>
    </div>
  );
}
