"use client";

import React, { useEffect, useState } from 'react';
import { useCart } from '@/context/CartContext';
import { useAuth } from '@/context/AuthContext';
import { Button } from '@/components/ui/button';
import { Container } from '@/components/ui/container';
import { Separator } from '@/components/ui/separator';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ShoppingBag, CreditCard, MapPin, User } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useToast } from '@/context/ToastContext';
import { orderService } from '@/services/orderService';

const CheckoutPage: React.FC = () => {
  const { cart, clearCart } = useCart();
  const { isAuthenticated, user } = useAuth();
  const { showToast } = useToast();
  const router = useRouter();
  
  const [isProcessing, setIsProcessing] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState<'card' | 'cash'>('card');
  const [formData, setFormData] = useState({
    email: user?.email || '',
    firstName: user?.name?.split(' ')[0] || '',
    lastName: user?.name?.split(' ')[1] || '',
    phone: '',
    address: '',
    city: '',
    postalCode: '',
    cardNumber: '',
    expiryDate: '',
    cvv: '',
  });

  // Auto-fill address from saved data
  useEffect(() => {
    const saved = orderService.getSavedShippingAddress();
    if (saved) {
      setFormData(prev => ({
        ...prev,
        firstName: prev.firstName || saved.firstName || '',
        lastName: prev.lastName || saved.lastName || '',
        email: prev.email || saved.email || '',
        phone: prev.phone || saved.phone || '',
        address: saved.address || prev.address,
        city: saved.city || prev.city,
        postalCode: saved.postalCode || prev.postalCode,
      }));
    }
  }, []);

  const formatPrice = (price: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    }).format(price);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!isAuthenticated) {
      showToast({
        type: 'error',
        title: 'يجب تسجيل الدخول',
        description: 'الرجاء تسجيل الدخول لإتمام عملية الشراء',
      });
      router.push('/login');
      return;
    }

    // Validate required fields
    if (!formData.firstName || !formData.lastName || !formData.address || !formData.city) {
      showToast({
        type: 'error',
        title: 'معلومات ناقصة',
        description: 'يرجى ملء جميع الحقول المطلوبة',
      });
      return;
    }

    // Validate phone if provided (allow +, spaces; require 7-15 digits)
    if (formData.phone) {
      const digitsOnly = formData.phone.replace(/[^0-9]/g, '');
      if (digitsOnly.length < 7 || digitsOnly.length > 15) {
        showToast({
          type: 'error',
          title: 'رقم هاتف غير صالح',
          description: 'يرجى إدخال رقم هاتف صحيح (7-15 أرقام)',
        });
        return;
      }
    }

    // Validate card details if paying by card
    if (paymentMethod === 'card' && (!formData.cardNumber || !formData.expiryDate || !formData.cvv)) {
      showToast({
        type: 'error',
        title: 'معلومات البطاقة ناقصة',
        description: 'يرجى ملء جميع معلومات البطاقة',
      });
      return;
    }

    setIsProcessing(true);

    try {
      // Create order via API
      const orderData = {
        shipping_address: {
          firstName: formData.firstName,
          lastName: formData.lastName,
          email: formData.email,
          phone: formData.phone,
          address: formData.address,
          city: formData.city,
          postalCode: formData.postalCode,
        },
        payment_method: paymentMethod,
        cart_items: cart.items.map(item => ({
          product_id: item.productId,
          quantity: item.quantity,
          price: item.price,
        })),
      };

      await orderService.createOrder(orderData);
      
      // Clear cart after successful order
      await clearCart();
      
      showToast({
        type: 'success',
        title: 'تم الطلب بنجاح!',
        description: 'تم تقديم طلبك بنجاح',
        duration: 5000,
      });
      
      router.push('/order');
    } catch (error) {
      console.error('Order creation error:', error);
      showToast({
        type: 'error',
        title: 'فشل الطلب',
        description: error instanceof Error ? error.message : 'حدث خطأ أثناء معالجة الطلب',
      });
    } finally {
      setIsProcessing(false);
    }
  };

  const subtotal = cart.totalPrice;
  const tax = subtotal * 0.1;
  const shipping = subtotal > 50 ? 0 : 9.99;
  const total = subtotal + tax + shipping;

  if (cart.items.length === 0) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Container className="py-12">
          <div className="text-center py-16">
            <ShoppingBag className="mx-auto h-24 w-24 text-gray-400 mb-6" />
            <h2 className="text-2xl font-bold text-gray-900 mb-4">عربة التسوق فارغة</h2>
            <p className="text-gray-600 mb-8">أضف بعض المنتجات إلى عربة التسوق للمتابعة</p>
            <Button asChild className="bg-black hover:bg-gray-800 text-white px-8 py-3">
              <Link href="/products">متابعة التسوق</Link>
            </Button>
          </div>
        </Container>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Container className="py-8 px-2">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">الدفع</h1>
          <p className="text-gray-600">أكمل عملية الشراء</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Checkout Form */}
          <div className="space-y-6">
            {/* Contact Information */}
            <div className="bg-white rounded-lg shadow-sm border p-6">
              <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                <User className="h-5 w-5" />
                معلومات الاتصال
              </h2>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="email" className='mb-2'>البريد الإلكتروني</Label>
                  <Input
                    id="email"
                    name="email"
                    type="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="firstName" className='mb-2'>الاسم الأول</Label>
                    <Input
                      id="firstName"
                      name="firstName"
                      value={formData.firstName}
                      onChange={handleInputChange}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="lastName" className='mb-2'>الاسم الأخير</Label>
                    <Input
                      id="lastName"
                      name="lastName"
                      value={formData.lastName}
                      onChange={handleInputChange}
                      required
                    />
                  </div>
                </div>
                <div>
                  <Label htmlFor="phone" className='mb-2'>رقم الهاتف</Label>
                  <Input
                    id="phone"
                    name="phone"
                    type="tel"
                    value={formData.phone}
                    onChange={handleInputChange}
                  />
                </div>
              </div>
            </div>

            {/* Shipping Address */}
            <div className="bg-white rounded-lg shadow-sm border p-6">
              <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                <MapPin className="h-5 w-5" />
                عنوان الشحن
              </h2>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="address" className='mb-2'>العنوان</Label>
                  <Input
                    id="address"
                    name="address"
                    value={formData.address}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="city" className='mb-2'>المدينة</Label>
                    <Input
                      id="city"
                      name="city"
                      value={formData.city}
                      onChange={handleInputChange}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="postalCode" className='mb-2'>الرمز البريدي</Label>
                    <Input
                      id="postalCode"
                      name="postalCode"
                      value={formData.postalCode}
                      onChange={handleInputChange}
                      required
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* Payment Information */}
            <div className="bg-white rounded-lg shadow-sm border p-6">
              <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                <CreditCard className="h-5 w-5" />
                معلومات الدفع
              </h2>
              
              {/* Payment Method Switch */}
              <div className="mb-6 space-y-4">
                <Label className="text-base font-medium">طريقة الدفع</Label>
                <div className="flex gap-4">
                  <button
                    type="button"
                    onClick={() => setPaymentMethod('card')}
                    className={`flex-1 p-4 rounded-lg border-2 transition-all ${
                      paymentMethod === 'card'
                        ? 'border-black bg-black text-white'
                        : 'border-gray-200 bg-white text-gray-900 hover:border-gray-300'
                    }`}
                  >
                    <div className="flex items-center justify-center gap-2">
                      <CreditCard className="h-5 w-5" />
                      <span className="font-medium">بطاقة ائتمانية</span>
                    </div>
                  </button>
                  
                  <button
                    type="button"
                    onClick={() => setPaymentMethod('cash')}
                    className={`flex-1 p-4 rounded-lg border-2 transition-all ${
                      paymentMethod === 'cash'
                        ? 'border-black bg-black text-white'
                        : 'border-gray-200 bg-white text-gray-900 hover:border-gray-300'
                    }`}
                  >
                    <div className="flex items-center justify-center gap-2">
                      <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
                      </svg>
                      <span className="font-medium">دفع عند الاستلام</span>
                    </div>
                  </button>
                </div>
              </div>

              {/* Card Details - Only show when card payment is selected */}
              {paymentMethod === 'card' && (
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="cardNumber" className='mb-2'>رقم البطاقة</Label>
                    <Input
                      id="cardNumber"
                      name="cardNumber"
                      placeholder="1234 5678 9012 3456"
                      value={formData.cardNumber}
                      onChange={handleInputChange}
                      required
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="expiryDate" className='mb-2'>تاريخ الانتهاء</Label>
                      <Input
                        id="expiryDate"
                        name="expiryDate"
                        placeholder="MM/YY"
                        value={formData.expiryDate}
                        onChange={handleInputChange}
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="cvv" className='mb-2'>CVV</Label>
                      <Input
                        id="cvv"
                        name="cvv"
                        placeholder="123"
                        value={formData.cvv}
                        onChange={handleInputChange}
                        required
                      />
                    </div>
                  </div>
                </div>
              )}

              {/* Cash on Delivery Message */}
              {paymentMethod === 'cash' && (
                <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                  <div className="flex items-start gap-3">
                    <svg className="h-5 w-5 text-green-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <div>
                      <h4 className="font-medium text-green-900 mb-1">الدفع عند الاستلام</h4>
                      <p className="text-sm text-green-700">
                        ادفع نقداً عند استلام طلبك. يرجى التأكد من توفر المبلغ الكامل عند التسليم.
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Order Summary */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg shadow-sm border p-6 sticky top-8">
              <h2 className="text-xl font-semibold mb-6">ملخص الطلب</h2>
              
              {/* Cart Items */}
              <div className="space-y-4 mb-6">
                {cart.items.map((item) => (
                  <div key={item.id} className="flex gap-3">
                    <div className="relative h-16 w-16 rounded-lg overflow-hidden bg-gray-100 flex-shrink-0">
                      {item.imageSrc.startsWith('data:image') ? (
                        // Use Next.js Image even for base64/data URLs but disable optimization
                        <Image
                          src={item.imageSrc}
                          alt={item.title}
                          fill
                          unoptimized
                          className="object-cover"
                        />
                      ) : (
                        // Use Next.js Image component for URLs
                        <Image
                          src={item.imageSrc}
                          alt={item.title}
                          fill
                          className="object-cover"
                        />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <h4 className="text-sm font-medium text-gray-900 truncate">
                        {item.title}
                      </h4>
                      <p className="text-sm text-gray-600">
                        Qty: {item.quantity}
                      </p>
                      <p className="text-sm font-medium">
                        {formatPrice(item.price * item.quantity)}
                      </p>
                    </div>
                  </div>
                ))}
              </div>

              <Separator className="my-4" />
              
              {/* Pricing Breakdown */}
              <div className="space-y-3">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">المجموع الفرعي</span>
                  <span className="font-medium">{formatPrice(subtotal)}</span>
                </div>
                
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">الشحن</span>
                  <span className="font-medium">
                    {shipping === 0 ? 'مجاني' : formatPrice(shipping)}
                  </span>
                </div>
                
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">الضريبة</span>
                  <span className="font-medium">{formatPrice(tax)}</span>
                </div>
                
                <Separator />
                
                <div className="flex justify-between text-lg font-semibold">
                  <span>المجموع</span>
                  <span>{formatPrice(total)}</span>
                </div>
              </div>

              <form onSubmit={handleSubmit} className="mt-6">
                <Button 
                  type="submit"
                  disabled={isProcessing}
                  className="w-full bg-black hover:bg-gray-800 text-white py-3"
                >
                  {isProcessing 
                    ? 'جاري المعالجة...' 
                    : paymentMethod === 'cash' 
                      ? 'تأكيد الطلب'
                      : `ادفع ${formatPrice(total)}`
                  }
                </Button>
              </form>

              <div className="mt-4 text-xs text-gray-500 text-center">
                {paymentMethod === 'card' ? (
                  <p>دفع آمن بحماية تشفير SSL</p>
                ) : (
                  <p>سيتم الدفع نقداً عند استلام الطلب</p>
                )}
              </div>
            </div>
          </div>
        </div>
      </Container>
    </div>
  );
};

export default CheckoutPage;