'use client';

import { useState } from 'react';
import { motion } from 'framer-motion';
import {
  ShoppingCart,
  Plus,
  Minus,
  Trash2,
  Package,
  CreditCard,
  Truck,
  CheckCircle,
  AlertCircle,
  Loader2,
} from 'lucide-react';
import { useSandbox } from './sandbox-context';

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

export function DemoOrderForm() {
  const { isRunning, logClick, logInput, logSubmit, simulateFetch, mockData } = useSandbox();
  const [cart, setCart] = useState<CartItem[]>([
    { id: 'prod-001', name: 'Familiar License', price: 299, quantity: 1 },
    { id: 'prod-002', name: 'Enterprise Support', price: 499, quantity: 1 },
  ]);
  const [customerName, setCustomerName] = useState('');
  const [customerEmail, setCustomerEmail] = useState('');
  const [shipping, setShipping] = useState('standard');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitResult, setSubmitResult] = useState<{ success: boolean; message: string } | null>(null);

  const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  const shippingCost = shipping === 'express' ? 25 : 0;

  const handleQuantityChange = (id: string, delta: number) => {
    logClick(
      { type: 'button', id: `qty-${delta > 0 ? 'plus' : 'minus'}-${id}`, text: delta > 0 ? '+' : '-', selector: `button#qty-${id}` }
    );
    setCart(prev =>
      prev.map(item =>
        item.id === id
          ? { ...item, quantity: Math.max(1, item.quantity + delta) }
          : item
      )
    );
  };

  const handleRemove = (id: string) => {
    logClick(
      { type: 'button', id: `remove-${id}`, text: 'Remove', selector: `button#remove-${id}` }
    );
    setCart(prev => prev.filter(item => item.id !== id));
  };

  const handleInputChange = (field: string, value: string, setter: (v: string) => void) => {
    logInput(
      { type: 'input', id: field, selector: `input#${field}` },
      value
    );
    setter(value);
  };

  const handleShippingChange = (value: string) => {
    logClick(
      { type: 'radio', id: `shipping-${value}`, text: value, selector: `input[name="shipping"][value="${value}"]` }
    );
    setShipping(value);
  };

  const handleSubmit = async () => {
    if (!isRunning) {
      setSubmitResult({ success: false, message: 'Sandbox not running - start the sandbox first!' });
      return;
    }

    const formData = {
      customer: { name: customerName, email: customerEmail },
      items: cart,
      shipping,
      total: total + shippingCost,
    };

    logSubmit(
      { type: 'form', id: 'order-form', selector: 'form#order-form' },
      formData,
      '/api/orders',
      'POST'
    );

    setIsSubmitting(true);
    setSubmitResult(null);

    try {
      const result = await simulateFetch('POST', '/api/orders', formData);
      setSubmitResult({
        success: result.status === 200 || result.status === 201,
        message: result.status === 200 || result.status === 201
          ? `Order #${(result.response as { orderId?: string })?.orderId || 'ORD-' + Date.now()} created successfully!`
          : 'Order submission failed',
      });
    } catch (error) {
      setSubmitResult({
        success: false,
        message: 'Network error - check sandbox configuration',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto p-6">
      <div className="flex items-center gap-3 mb-6">
        <ShoppingCart className="w-6 h-6 text-brand" />
        <h2 className="text-xl font-bold text-white">Order Form</h2>
        <span className="text-xs bg-brand-secondary/20 text-brand-secondary-light px-2 py-1 rounded-full">
          Demo Artifact
        </span>
      </div>

      {/* Cart Items */}
      <div className="space-y-3 mb-6">
        {cart.map(item => (
          <motion.div
            key={item.id}
            layout
            className="flex items-center gap-4 p-4 rounded-xl bg-white/5 border border-white/10"
          >
            <Package className="w-8 h-8 text-brand" />
            <div className="flex-1">
              <div className="font-medium text-white">{item.name}</div>
              <div className="text-sm text-gray-400">${item.price.toFixed(2)}</div>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => handleQuantityChange(item.id, -1)}
                className="p-1.5 rounded-lg bg-white/5 hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
              >
                <Minus className="w-4 h-4" />
              </button>
              <span className="w-8 text-center text-white font-medium">{item.quantity}</span>
              <button
                onClick={() => handleQuantityChange(item.id, 1)}
                className="p-1.5 rounded-lg bg-white/5 hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
              >
                <Plus className="w-4 h-4" />
              </button>
            </div>
            <div className="w-24 text-right font-medium text-white">
              ${(item.price * item.quantity).toFixed(2)}
            </div>
            <button
              onClick={() => handleRemove(item.id)}
              className="p-1.5 rounded-lg hover:bg-red-500/20 text-gray-400 hover:text-red-400 transition-colors"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          </motion.div>
        ))}
      </div>

      {/* Customer Info */}
      <div className="space-y-4 mb-6">
        <h3 className="font-medium text-white">Customer Information</h3>
        <div className="grid grid-cols-2 gap-4">
          <input
            type="text"
            id="customerName"
            placeholder="Full Name"
            value={customerName}
            onChange={(e) => handleInputChange('customerName', e.target.value, setCustomerName)}
            className="px-4 py-3 rounded-xl bg-white/5 border border-white/10 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
          />
          <input
            type="email"
            id="customerEmail"
            placeholder="Email Address"
            value={customerEmail}
            onChange={(e) => handleInputChange('customerEmail', e.target.value, setCustomerEmail)}
            className="px-4 py-3 rounded-xl bg-white/5 border border-white/10 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-brand-deep/50"
          />
        </div>
      </div>

      {/* Shipping */}
      <div className="mb-6">
        <h3 className="font-medium text-white mb-3">Shipping Method</h3>
        <div className="flex gap-4">
          <label
            className={`flex-1 flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-colors ${
              shipping === 'standard'
                ? 'bg-brand-deep/10 border-brand-deep/30'
                : 'bg-white/5 border-white/10 hover:bg-white/10'
            }`}
            onClick={() => handleShippingChange('standard')}
          >
            <Truck className={`w-5 h-5 ${shipping === 'standard' ? 'text-brand' : 'text-gray-400'}`} />
            <div>
              <div className="font-medium text-white">Standard</div>
              <div className="text-sm text-gray-400">Free • 5-7 days</div>
            </div>
          </label>
          <label
            className={`flex-1 flex items-center gap-3 p-4 rounded-xl border cursor-pointer transition-colors ${
              shipping === 'express'
                ? 'bg-brand-deep/10 border-brand-deep/30'
                : 'bg-white/5 border-white/10 hover:bg-white/10'
            }`}
            onClick={() => handleShippingChange('express')}
          >
            <Truck className={`w-5 h-5 ${shipping === 'express' ? 'text-brand' : 'text-gray-400'}`} />
            <div>
              <div className="font-medium text-white">Express</div>
              <div className="text-sm text-gray-400">$25 • 1-2 days</div>
            </div>
          </label>
        </div>
      </div>

      {/* Total */}
      <div className="flex items-center justify-between p-4 rounded-xl bg-white/5 border border-white/10 mb-6">
        <div>
          <div className="text-gray-400">Subtotal</div>
          <div className="text-2xl font-bold text-white">${total.toFixed(2)}</div>
        </div>
        {shippingCost > 0 && (
          <div className="text-right">
            <div className="text-gray-400">+ Shipping</div>
            <div className="text-lg text-brand">${shippingCost.toFixed(2)}</div>
          </div>
        )}
        <div className="text-right">
          <div className="text-gray-400">Total</div>
          <div className="text-2xl font-bold gradient-text">${(total + shippingCost).toFixed(2)}</div>
        </div>
      </div>

      {/* Submit Result */}
      {submitResult && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className={`mb-4 p-4 rounded-xl flex items-center gap-3 ${
            submitResult.success
              ? 'bg-green-500/10 border border-green-500/30 text-green-400'
              : 'bg-red-500/10 border border-red-500/30 text-red-400'
          }`}
        >
          {submitResult.success ? <CheckCircle className="w-5 h-5" /> : <AlertCircle className="w-5 h-5" />}
          {submitResult.message}
        </motion.div>
      )}

      {/* Submit */}
      <button
        onClick={handleSubmit}
        disabled={isSubmitting || cart.length === 0}
        className="w-full flex items-center justify-center gap-2 px-6 py-4 rounded-xl font-semibold text-white bg-gradient-to-r from-brand-deep to-brand-secondary hover:from-brand hover:to-brand-secondary-light disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg shadow-brand-deep/25"
      >
        {isSubmitting ? (
          <><Loader2 className="w-5 h-5 animate-spin" /> Processing...</>
        ) : (
          <><CreditCard className="w-5 h-5" /> Place Order</>
        )}
      </button>
    </div>
  );
}
