import { useState } from 'react';
import { useCartStore } from '../../stores/cart';
import ShippingForm from './ShippingForm';
import PaymentMethod from './PaymentMethod';
import OrderSummary from './OrderSummary';

type Step = 'shipping' | 'payment' | 'review';

export default function CheckoutForm() {
  const [step, setStep] = useState<Step>('shipping');
  const [shippingData, setShippingData] = useState<any>(null);
  const [paymentMethod, setPaymentMethod] = useState<'payso' | 'stripe'>('payso');
  const [isProcessing, setIsProcessing] = useState(false);
  const { items, clearCart } = useCartStore();

  const handleShippingSubmit = (data: any) => {
    setShippingData(data);
    setStep('payment');
  };

  const handlePaymentSubmit = async () => {
    setIsProcessing(true);
    try {
      // Create order
      const orderRes = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items, shippingAddress: shippingData })
      });
      const { order } = await orderRes.json();
      
      // Create payment
      const paymentRes = await fetch('/api/payments/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ orderId: order.id })
      });
      const { paymentUrl } = await paymentRes.json();
      
      // Redirect to PaySo
      window.location.href = paymentUrl;
    } catch (error) {
      console.error(error);
      setIsProcessing(false);
    }
  };

  return (
    <div className="grid lg:grid-cols-3 gap-8">
      <div className="lg:col-span-2">
        <div className="flex gap-4 mb-8">
          {['shipping', 'payment', 'review'].map((s, i) => (
            <div key={s} className={`flex-1 text-center pb-2 ${step === s ? 'border-b-2 border-blue-600' : ''}`}>
              <span className="text-sm text-gray-500">ขั้นตอน {i + 1}</span>
              <p className="font-medium">{s === 'shipping' ? 'ที่อยู่จัดส่ง' : s === 'payment' ? 'ชำระเงิน' : 'สรุป'}</p>
            </div>
          ))}
        </div>

        {step === 'shipping' && <ShippingForm onSubmit={handleShippingSubmit} />}
        {step === 'payment' && (
          <PaymentMethod 
            value={paymentMethod} 
            onChange={setPaymentMethod}
            onContinue={handlePaymentSubmit}
            isProcessing={isProcessing}
          />
        )}
        {step === 'review' && (
          <div className="bg-gray-50 p-6 rounded-lg">
            <h3 className="font-medium mb-4">สรุปคำสั่งซื้อ</h3>
            <pre>{JSON.stringify({ shippingData, paymentMethod }, null, 2)}</pre>
          </div>
        )}
      </div>
      <div>
        <OrderSummary />
      </div>
    </div>
  );
}
