'use client';

import React, { useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { Loader, Check, X, ShoppingCart, CreditCard, Truck } from 'lucide-react';

interface CartItem {
  name: string;
  price: number;
  quantity: number;
}

const CheckoutFlow: React.FC = () => {
  const [step, setStep] = useState(1);
  const [cart, setCart] = useState<CartItem[]>([]);
  const [shippingAddress, setShippingAddress] = useState({
    name: '',
    address: '',
    city: '',
    zip: '',
  });
  const [discountCode, setDiscountCode] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleNextStep = () => setStep((prev) => prev + 1);
  const handlePreviousStep = () => setStep((prev) => prev - 1);

  const handleApplyDiscount = async () => {
    setIsLoading(true);
    setError(null);
    try {
      // Simulate discount code validation
      await new Promise((resolve) => setTimeout(resolve, 1000));
      alert('Discount code applied successfully!');
    } catch (err) {
      setError('Failed to apply discount code.');
    } finally {
      setIsLoading(false);
    }
  };

  const handlePlaceOrder = async () => {
    setIsLoading(true);
    setError(null);
    try {
      // Simulate order placement
      await fetch('/api/swag/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ cart, shippingAddress, discountCode }),
      });
      setStep(4); // Move to order confirmation
    } catch (err) {
      setError('Failed to place order. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const renderStepContent = () => {
    switch (step) {
      case 1:
        return (
          <div>
            <h2 className="text-xl font-semibold mb-4">Cart Summary</h2>
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-xl p-4">
              {cart.length === 0 ? (
                <p>Your cart is empty.</p>
              ) : (
                <ul>
                  {cart.map((item, index) => (
                    <li key={index} className="flex justify-between py-2">
                      <span>{item.name}</span>
                      <span>${item.price.toFixed(2)}</span>
                    </li>
                  ))}
                </ul>
              )}
            </div>
            <div className="mt-4">
              <label className="block text-sm mb-2">Discount Code</label>
              <div className="flex items-center gap-2">
                <input
                  type="text"
                  className="w-full p-2 bg-brand-bg border border-white/10 rounded-lg text-white"
                  value={discountCode}
                  onChange={(e) => setDiscountCode(e.target.value)}
                />
                <button
                  className="bg-brand text-white px-4 py-2 rounded-lg hover:bg-brand-deep transition"
                  onClick={handleApplyDiscount}
                  disabled={isLoading}
                >
                  {isLoading ? <Loader className="animate-spin" size={16} /> : 'Apply'}
                </button>
              </div>
              {error && <p className="text-red-400 mt-2">{error}</p>}
            </div>
          </div>
        );
      case 2:
        return (
          <div>
            <h2 className="text-xl font-semibold mb-4">Shipping Address</h2>
            <form className="space-y-4">
              <div>
                <label className="block text-sm mb-2">Name</label>
                <input
                  type="text"
                  className="w-full p-2 bg-brand-bg border border-white/10 rounded-lg text-white"
                  value={shippingAddress.name}
                  onChange={(e) =>
                    setShippingAddress({ ...shippingAddress, name: e.target.value })
                  }
                />
              </div>
              <div>
                <label className="block text-sm mb-2">Address</label>
                <input
                  type="text"
                  className="w-full p-2 bg-brand-bg border border-white/10 rounded-lg text-white"
                  value={shippingAddress.address}
                  onChange={(e) =>
                    setShippingAddress({ ...shippingAddress, address: e.target.value })
                  }
                />
              </div>
              <div className="flex gap-4">
                <div className="flex-1">
                  <label className="block text-sm mb-2">City</label>
                  <input
                    type="text"
                    className="w-full p-2 bg-brand-bg border border-white/10 rounded-lg text-white"
                    value={shippingAddress.city}
                    onChange={(e) =>
                      setShippingAddress({ ...shippingAddress, city: e.target.value })
                    }
                  />
                </div>
                <div className="flex-1">
                  <label className="block text-sm mb-2">ZIP Code</label>
                  <input
                    type="text"
                    className="w-full p-2 bg-brand-bg border border-white/10 rounded-lg text-white"
                    value={shippingAddress.zip}
                    onChange={(e) =>
                      setShippingAddress({ ...shippingAddress, zip: e.target.value })
                    }
                  />
                </div>
              </div>
            </form>
          </div>
        );
      case 3:
        return (
          <div>
            <h2 className="text-xl font-semibold mb-4">Payment Processing</h2>
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-xl p-4">
              <p>Enter your payment details to complete the purchase.</p>
            </div>
          </div>
        );
      case 4:
        return (
          <div>
            <h2 className="text-xl font-semibold mb-4">Order Confirmation</h2>
            <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-xl p-4">
              <p>Thank you for your order! You will receive a confirmation email shortly.</p>
            </div>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="max-w-2xl mx-auto bg-brand-bg text-white p-6 rounded-xl">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Checkout</h1>
        <div className="flex items-center gap-2">
          <ShoppingCart size={24} />
          <Truck size={24} />
          <CreditCard size={24} />
        </div>
      </div>
      {renderStepContent()}
      <div className="flex justify-between mt-6">
        {step > 1 && (
          <button
            className="bg-brand-secondary-light text-white px-4 py-2 rounded-lg hover:bg-brand-secondary transition"
            onClick={handlePreviousStep}
          >
            Back
          </button>
        )}
        {step < 4 && (
          <button
            className="bg-brand text-white px-4 py-2 rounded-lg hover:bg-brand-deep transition"
            onClick={step === 3 ? handlePlaceOrder : handleNextStep}
            disabled={isLoading}
          >
            {isLoading ? <Loader className="animate-spin" size={16} /> : 'Next'}
          </button>
        )}
      </div>
    </div>
  );
};

export default CheckoutFlow;