import { useState, useMemo } from 'react';
import { useEquipmentStore } from '@/stores/equipmentStore';
import { useStudentStore } from '@/stores/studentStore';
import { useUIStore } from '@/stores/uiStore';
import { format } from 'date-fns';
import { Loader2, X, ShoppingBag, TrendingUp, TrendingDown } from 'lucide-react';

export default function RecordSellScreen() {
  const { items, recordSell } = useEquipmentStore();
  const { students } = useStudentStore();
  const { goBack, showToast } = useUIStore();
  const [equipmentId, setEquipmentId] = useState<number | ''>('');
  const [buyerType, setBuyerType] = useState<'student' | 'external'>('student');
  const [buyerId, setBuyerId] = useState<number | ''>('');
  const [buyerName, setBuyerName] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [unitSellingPrice, setUnitSellingPrice] = useState('');
  const [saleDate, setSaleDate] = 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 unitCost = selectedItem?.unitCost || 0;
  const sellingPrice = Number(unitSellingPrice) || 0;
  const totalCost = unitCost * quantity;
  const totalRevenue = sellingPrice * quantity;
  const profit = totalRevenue - totalCost;
  const isProfit = profit >= 0;
  const stockError = selectedItem ? quantity > selectedItem.currentStock : false;

  const handleSubmit = async () => {
    if (!equipmentId || !unitSellingPrice || quantity < 1) {
      showToast({ type: 'error', message: 'Fill all required fields' });
      return;
    }
    if (stockError) {
      showToast({ type: 'error', message: `Only ${selectedItem?.currentStock} units in stock!` });
      return;
    }
    setIsSaving(true);
    await recordSell({
      equipmentId: Number(equipmentId),
      quantity,
      unitSellingPrice: sellingPrice,
      buyerName: buyerType === 'student' 
        ? students.find(s => s.id === Number(buyerId))?.fullName || undefined 
        : buyerName || undefined,
      saleDate,
      notes: notes || undefined,
    });
    setIsSaving(false);
    showToast({ type: 'success', message: `Sold ${quantity} units. Profit: Rs.${Math.abs(profit)} ${isProfit ? 'Profit' : 'Loss'}` });
    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-emerald-50 rounded-lg flex items-center justify-center">
            <ShoppingBag className="w-4 h-4 text-emerald-500" />
          </div>
          <h2 className="text-lg font-bold text-gray-900">Record Sale</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) setUnitSellingPrice((item.unitCost * 1.3).toFixed(0));
          }} className={inputClass}>
            <option value="">Select equipment...</option>
            {items.map(i => <option key={i.id} value={i.id}>{i.name} (Stock: {i.currentStock} @ Rs.{i.unitCost})</option>)}
          </select>
        </div>

        {selectedItem && (
          <div className="bg-gray-50 rounded-xl p-3 text-xs">
            <div className="flex justify-between"><span className="text-gray-500">Unit Cost</span><span className="font-medium">Rs.{selectedItem.unitCost}</span></div>
            <div className="flex justify-between mt-1"><span className="text-gray-500">In Stock</span><span className={`font-medium ${selectedItem.currentStock < 5 ? 'text-red-500' : 'text-gray-800'}`}>{selectedItem.currentStock} units</span></div>
          </div>
        )}

        {/* Buyer Type */}
        <div>
          <label className={labelClass}>Buyer</label>
          <div className="flex bg-gray-100 rounded-full p-0.5">
            <button onClick={() => setBuyerType('student')} className={`flex-1 py-2 text-xs font-medium rounded-full transition-all ${buyerType === 'student' ? 'bg-white text-orange-600 shadow-sm' : 'text-gray-500'}`}>Student</button>
            <button onClick={() => setBuyerType('external')} className={`flex-1 py-2 text-xs font-medium rounded-full transition-all ${buyerType === 'external' ? 'bg-white text-orange-600 shadow-sm' : 'text-gray-500'}`}>External</button>
          </div>
        </div>

        {buyerType === 'student' ? (
          <div>
            <label className={labelClass}>Select Student</label>
            <select value={buyerId} onChange={e => setBuyerId(Number(e.target.value))} className={inputClass}>
              <option value="">Select...</option>
              {students.filter(s => s.isActive).map(s => <option key={s.id} value={s.id}>{s.fullName} ({s.studentId})</option>)}
            </select>
          </div>
        ) : (
          <div>
            <label className={labelClass}>Buyer Name</label>
            <input type="text" value={buyerName} onChange={e => setBuyerName(e.target.value)} placeholder="Customer name" className={inputClass} />
          </div>
        )}

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Quantity *</label>
            <input type="number" min={1} max={selectedItem?.currentStock} value={quantity} onChange={e => setQuantity(parseInt(e.target.value) || 1)} 
              className={`${inputClass} ${stockError ? 'border-red-400 focus:border-red-500' : ''}`} />
            {stockError && <p className="text-xs text-red-500 mt-1">Exceeds stock ({selectedItem?.currentStock})</p>}
          </div>
          <div>
            <label className={labelClass}>Selling Price/Unit *</label>
            <input type="number" value={unitSellingPrice} onChange={e => setUnitSellingPrice(e.target.value)} placeholder="0.00" className={inputClass} />
          </div>
        </div>

        {/* Profit Calculation */}
        {equipmentId && unitSellingPrice && (
          <div className={`rounded-xl p-4 border ${isProfit ? 'bg-emerald-50 border-emerald-200' : 'bg-red-50 border-red-200'}`}>
            <div className="flex items-center gap-2 mb-3">
              {isProfit ? <TrendingUp className="w-5 h-5 text-emerald-500" /> : <TrendingDown className="w-5 h-5 text-red-500" />}
              <span className={`text-sm font-bold ${isProfit ? 'text-emerald-700' : 'text-red-700'}`}>{isProfit ? 'PROFIT' : 'LOSS'}</span>
            </div>
            <div className="space-y-1.5">
              <div className="flex justify-between text-sm"><span className="text-gray-500">Total Sale</span><span className="font-semibold text-gray-800">Rs.{totalRevenue.toLocaleString('en-IN')}</span></div>
              <div className="flex justify-between text-sm"><span className="text-gray-500">Total Cost</span><span className="font-semibold text-gray-800">Rs.{totalCost.toLocaleString('en-IN')}</span></div>
              <div className="border-t border-current opacity-20 pt-1.5 flex justify-between text-base font-bold">
                <span className={isProfit ? 'text-emerald-700' : 'text-red-700'}>Net {isProfit ? 'Profit' : 'Loss'}</span>
                <span className={isProfit ? 'text-emerald-700' : 'text-red-700'}>Rs.{Math.abs(profit).toLocaleString('en-IN')}</span>
              </div>
            </div>
          </div>
        )}

        <div>
          <label className={labelClass}>Sale Date</label>
          <input type="date" value={saleDate} onChange={e => setSaleDate(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 || stockError}
          className="w-full h-12 bg-emerald-500 text-white font-semibold rounded-xl shadow-lg shadow-emerald-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 Sale'}
        </button>
      </div>
    </div>
  );
}
