import React, { useState, useCallback, useRef, useEffect } from 'react';
import {
  UploadCloudIcon, TypeIcon, MapPinIcon, DollarSignIcon, PhoneIcon, XIcon, ChevronDownIcon,
  CrosshairIcon, HomeIcon, ListIcon, ECommerceIcon, UserIcon, CrmIcon, SearchIcon, LinkIcon, CheckIcon
} from '../Icons';
declare const L: any;
type PurchaseMode = 'request' | 'accept';
type LocationField = 'delivery';
type Currency = 'IRT' | 'USD' | 'CAD' | 'IQD';
interface ImageFile {
  id: number;
  url: string;
  file: File;
}
interface RegisterOnlinePurchasePageProps {
  showError: (message: string) => void;
  showSuccess: (message: string) => void;
}
import { API_BASE_URL } from '@/src/config.js';
const RegisterOnlinePurchasePage: React.FC<RegisterOnlinePurchasePageProps> = ({ showError, showSuccess }) => {
  const [purchaseMode, setPurchaseMode] = useState<PurchaseMode>('request');
  const [images, setImages] = useState<ImageFile[]>([]);
  const [shopperImages, setShopperImages] = useState<ImageFile[]>([]);
  const [currency, setCurrency] = useState<Currency>('IRT');
  const [showPhoneNumber, setShowPhoneNumber] = useState(false);
  const [modalState, setModalState] = useState<{ isOpen: boolean; field: LocationField | null }>({ isOpen: false, field: null });
  const [deliveryLocation, setDeliveryLocation] = useState<{ lat: number; lng: number } | null>(null);
  const [deliveryCountry, setDeliveryCountry] = useState('');
  const [deliveryCity, setDeliveryCity] = useState('');
  const [deliveryAddress, setDeliveryAddress] = useState('');
  const [shopperCountry, setShopperCountry] = useState('');
  const [shopperCity, setShopperCity] = useState('');
  const [feeDescription, setFeeDescription] = useState('');
  const [capabilities, setCapabilities] = useState('');
  const [serviceTitle, setServiceTitle] = useState('');
  const [categories, setCategories] = useState<string[]>([]);
  const [supportedSites, setSupportedSites] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [title, setTitle] = useState('');
  const [link, setLink] = useState('');
  const [description, setDescription] = useState('');
  const [itemPrice, setItemPrice] = useState<number | ''>('');
  const [proposedFee, setProposedFee] = useState<number | ''>('');

  const deliveryLocationText = deliveryLocation
    ? `${deliveryLocation.lat.toFixed(5)}, ${deliveryLocation.lng.toFixed(5)}`
    : '';

  const currencies = [
    { value: 'IRT', label: 'تومان' },
    { value: 'USD', label: 'دلار آمریکا' },
    { value: 'CAD', label: 'دلار کانادا' },
    { value: 'IQD', label: 'دینار' },
  ];

  const categoryOptions = [
    { value: 'electronics', label: 'الکترونیک' },
    { value: 'fashion', label: 'مد و پوشاک' },
    { value: 'books', label: 'کتاب و رسانه' },
    { value: 'home', label: 'خانه و آشپزخانه' },
    { value: 'beauty', label: 'آرایشی و بهداشتی' },
    { value: 'other', label: 'سایر' },
  ];

  useEffect(() => {
    return () => {
      [...images, ...shopperImages].forEach(img => URL.revokeObjectURL(img.url));
    };
  }, [images, shopperImages]);

  const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>, target: 'request' | 'shopper') => {
    const files = event.target.files;
    if (files) {
      const newImages: ImageFile[] = Array.from(files).map((file: File) => ({
        id: Date.now() + Math.random(),
        url: URL.createObjectURL(file),
        file,
      }));
      if (target === 'request') {
        setImages(prev => [...prev, ...newImages]);
      } else {
        setShopperImages(prev => [...prev, ...newImages]);
      }
    }
  };

  const removeImage = (id: number, target: 'request' | 'shopper') => {
    const setter = target === 'request' ? setImages : setShopperImages;
    setter(prev => {
      const imgToRemove = prev.find(img => img.id === id);
      if (imgToRemove) URL.revokeObjectURL(imgToRemove.url);
      return prev.filter(img => img.id !== id);
    });
  };

  const onDrop = useCallback((event: React.DragEvent<HTMLLabelElement>, target: 'request' | 'shopper') => {
    event.preventDefault();
    event.stopPropagation();
    const files = event.dataTransfer.files;
    if (files && files.length > 0) {
      const newImages: ImageFile[] = Array.from(files)
        .filter((file: File) => file.type.startsWith('image/'))
        .map((file: File) => ({
          id: Date.now() + Math.random(),
          url: URL.createObjectURL(file),
          file,
        }));
      if (target === 'request') {
        setImages(prev => [...prev, ...newImages]);
      } else {
        setShopperImages(prev => [...prev, ...newImages]);
      }
    }
  }, []);

  const onDragOver = (event: React.DragEvent<HTMLLabelElement>) => {
    event.preventDefault();
    event.stopPropagation();
  };

  const openModal = (field: LocationField) => {
    setModalState({ isOpen: true, field });
  };

  const closeModal = () => {
    setModalState({ isOpen: false, field: null });
  };

  const confirmLocation = (location: { lat: number; lng: number }) => {
    if (modalState.field === 'delivery') {
      setDeliveryLocation(location);
    }
    closeModal();
  };

  // ================== Submit Request ==================
  const handleSubmitRequest = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    if (!title.trim() || itemPrice === '' || proposedFee === '') {
      showError('لطفاً فیلدهای اجباری (عنوان، قیمت کالا، هزینه پیشنهادی) را پر کنید.');
      setLoading(false);
      return;
    }

    const formData = new FormData();
    // اطلاعات اصلی
    formData.append('title', title.trim());
    if (link) formData.append('link', link);
    if (description) formData.append('description', description);
    // موقعیت تحویل
    if (deliveryLocation) {
      formData.append('delivery_lat', deliveryLocation.lat.toString());
      formData.append('delivery_lng', deliveryLocation.lng.toString());
    }
    if (deliveryCountry) formData.append('delivery_country', deliveryCountry);
    if (deliveryCity) formData.append('delivery_city', deliveryCity);
    if (deliveryAddress) formData.append('delivery_address', deliveryAddress);
    // قیمت‌گذاری
    formData.append('item_price', itemPrice.toString());
    formData.append('proposed_fee', proposedFee.toString());
    formData.append('currency', currency);
    // اطلاعات تماس
    formData.append('show_phone', showPhoneNumber ? '1' : '0');
    // تصاویر
    images.forEach(img => formData.append('images[]', img.file));

    try {
      const response = await fetch(`${API_BASE_URL}/online-purchase/request`, {
        method: 'POST',
        headers: {
          'X-Auth-Token': localStorage.getItem('auth_token') || ''
        },
        body: formData
      });
      
      const result = await response.json();
      if (!response.ok) {
        const errorMessage = result.message || 'خطا در ثبت درخواست';
        showError(errorMessage);
        return;
      }
      
      showSuccess('درخواست خرید با موفقیت ثبت شد!');
      // ریست فرم
      setTitle('');
      setLink('');
      setDescription('');
      setDeliveryLocation(null);
      setDeliveryCountry('');
      setDeliveryCity('');
      setDeliveryAddress('');
      setItemPrice('');
      setProposedFee('');
      setCurrency('IRT');
      setShowPhoneNumber(false);
      setImages([]);
    } catch (err: any) {
      console.error('خطا در ارسال درخواست خرید:', err);
      showError(err.message || 'خطا در ارتباط با سرور');
    } finally {
      setLoading(false);
    }
  };

  // ================== Submit Shopper ==================
  const handleSubmitShopper = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    if (!shopperCountry.trim() || !shopperCity.trim()) {
      showError('لطفاً کشور و شهر خود را وارد کنید.');
      setLoading(false);
      return;
    }

    const formData = new FormData();
    // اطلاعات اصلی
    formData.append('country', shopperCountry.trim());
    formData.append('city', shopperCity.trim());
    if (serviceTitle) formData.append('service_title', serviceTitle);
    // دسته‌بندی‌ها
    if (categories.length > 0) {
      categories.forEach(cat => formData.append('categories[]', cat));
    }
    // سایت‌های پشتیبانی شده
    if (supportedSites.length > 0) {
      supportedSites.forEach(site => formData.append('supported_sites[]', site));
    }
    // جزئیات خدمات
    if (feeDescription) formData.append('fee_description', feeDescription);
    if (capabilities) formData.append('capabilities', capabilities);
    // تصاویر
    if (shopperImages.length > 0) {
      shopperImages.forEach(img => formData.append('images[]', img.file));
    }
    // اطلاعات تماس
    formData.append('show_phone', showPhoneNumber ? '1' : '0');

    try {
      const response = await fetch(`${API_BASE_URL}/online-purchase/shopper`, {
        method: 'POST',
        headers: {
          'X-Auth-Token': localStorage.getItem('auth_token') || ''
        },
        body: formData
      });
      
      const result = await response.json();
      if (!response.ok) {
        const errorMessage = result.message || 'خطا در ثبت اطلاعات';
        showError(errorMessage);
        return;
      }
      
      showSuccess('اطلاعات شما با موفقیت ثبت شد!');
      // ریست فرم
      setShopperCountry('');
      setShopperCity('');
      setServiceTitle('');
      setCategories([]);
      setSupportedSites([]);
      setFeeDescription('');
      setCapabilities('');
      setShopperImages([]);
      setShowPhoneNumber(false);
    } catch (err: any) {
      console.error('خطا در ثبت اطلاعات خریدار:', err);
      showError(err.message || 'خطا در ارتباط با سرور');
    } finally {
      setLoading(false);
    }
  };

  // ریست فرم هنگام تغییر حالت
  useEffect(() => {
    // ریست فیلدهای مشترک
    setShowPhoneNumber(false);
    if (purchaseMode === 'request') {
      // ریست فیلدهای درخواست خرید
      setImages([]);
      setTitle('');
      setLink('');
      setDescription('');
      setDeliveryLocation(null);
      setDeliveryCountry('');
      setDeliveryCity('');
      setDeliveryAddress('');
      setItemPrice('');
      setProposedFee('');
      setCurrency('IRT');
    } else {
      // ریست فیلدهای خریدار
      setShopperImages([]);
      setShopperCountry('');
      setShopperCity('');
      setServiceTitle('');
      setCategories([]);
      setSupportedSites([]);
      setFeeDescription('');
      setCapabilities('');
    }
  }, [purchaseMode]);

  return (
    <div className="flex flex-col space-y-8">
      <div>
        <h1 className="text-3xl font-bold text-gray-800 dark:text-white">
          {purchaseMode === 'request' ? 'ثبت درخواست خرید اینترنتی' : 'اعلام آمادگی برای انجام خرید'}
        </h1>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          {purchaseMode === 'request'
            ? 'اطلاعات کالای مورد نظر خود برای خرید را ثبت کنید.'
            : 'اطلاعات خود را برای پذیرش سفارشات خرید ثبت کنید.'}
        </p>
      </div>
      <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
        <h3 className="text-lg font-semibold mb-4 text-center text-gray-800 dark:text-gray-200">
          نوع فعالیت خود را انتخاب کنید
        </h3>
        <div className="max-w-sm mx-auto">
          <div className="bg-custom-light-bg dark:bg-custom-dark-blue rounded-xl shadow-inner p-1">
            <div className="relative flex rounded-lg overflow-hidden">
              <span
                className={`absolute top-0 bottom-0 right-0 w-1/2 bg-custom-purple rounded-lg shadow-md transition-transform duration-300 ease-in-out ${
                  purchaseMode === 'accept' ? '-translate-x-full' : 'translate-x-0'
                }`}
                aria-hidden="true"
              />
              <button
                type="button"
                onClick={() => setPurchaseMode('request')}
                className={`relative z-10 flex w-1/2 items-center justify-center gap-2 rounded-lg py-2.5 text-md font-semibold transition-colors duration-300 ${
                  purchaseMode === 'request' ? 'text-white' : 'text-gray-600 dark:text-gray-300'
                }`}
                aria-label="درخواست خرید"
              >
                <ECommerceIcon className="h-5 w-5" />
                <span>درخواست خرید</span>
              </button>
              <button
                type="button"
                onClick={() => setPurchaseMode('accept')}
                className={`relative z-10 flex w-1/2 items-center justify-center gap-2 rounded-lg py-2.5 text-md font-semibold transition-colors duration-300 ${
                  purchaseMode === 'accept' ? 'text-white' : 'text-gray-600 dark:text-gray-300'
                }`}
                aria-label="قبول کردن خرید"
              >
                <UserIcon className="h-5 w-5" />
                <span>قبول کردن خرید</span>
              </button>
            </div>
          </div>
        </div>
      </div>
      {purchaseMode === 'request' ? (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-1 space-y-8">
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
              <h3 className="text-lg font-semibold mb-4">تصویر کالا</h3>
              <label
                htmlFor="file-upload-request"
                className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer bg-custom-light-bg dark:bg-custom-dark-blue hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                onDrop={(e) => onDrop(e, 'request')}
                onDragOver={onDragOver}
              >
                <div className="flex flex-col items-center justify-center pt-5 pb-6">
                  <UploadCloudIcon className="w-10 h-10 mb-3 text-gray-400" />
                  <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
                    <span className="font-semibold">برای آپلود کلیک کنید</span> یا بکشید
                  </p>
                  <p className="text-xs text-gray-400">فرمت‌های مجاز: JPG, PNG, GIF</p>
                </div>
                <input
                  id="file-upload-request"
                  type="file"
                  className="hidden"
                  multiple
                  accept="image/jpeg,image/png,image/gif"
                  onChange={(e) => handleImageUpload(e, 'request')}
                />
              </label>
            </div>
            {images.length > 0 && (
              <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                <h3 className="text-lg font-semibold mb-4">پیش‌نمایش ({images.length} تصویر)</h3>
                <div className="grid grid-cols-3 gap-4">
                  {images.map(image => (
                    <div key={image.id} className="relative group">
                      <img
                        src={image.url}
                        alt="Preview"
                        className="w-full h-24 object-cover rounded-md"
                      />
                      <button
                        type="button"
                        onClick={() => removeImage(image.id, 'request')}
                        className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                      >
                        <XIcon className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
          <div className="lg:col-span-2">
            <form className="space-y-8" onSubmit={handleSubmitRequest}>
              <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                  ۱. اطلاعات کالا
                </h3>
                <div className="mt-6 space-y-6">
                  <InputWithIcon
                    icon={TypeIcon}
                    id="title"
                    placeholder="مثال: گوشی موبایل سامسونگ"
                    label="عنوان کالا *"
                    value={title}
                    onChange={e => setTitle(e.target.value)}
                    required
                  />
                  <InputWithIcon
                    icon={LinkIcon}
                    id="link"
                    placeholder="https://example.com/product"
                    label="لینک خرید (اختیاری)"
                    value={link}
                    onChange={e => setLink(e.target.value)}
                  />
                  <TextareaWithIcon
                    icon={ListIcon}
                    id="description"
                    placeholder="جزئیات بیشتر در مورد کالا، رنگ، مدل، سایز و..."
                    label="توضیحات (اختیاری)"
                    value={description}
                    onChange={e => setDescription(e.target.value)}
                  />
                </div>
              </div>
              <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                  ۲. محل تحویل کالا
                </h3>
                <div className="mt-6">
                  <div className="border border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-4">
                    <h3 className="font-semibold text-lg text-gray-800 dark:text-gray-200">مقصد تحویل</h3>
                    <InputWithLocationButton
                      onButtonClick={() => openModal('delivery')}
                      value={deliveryLocationText}
                      id="destination"
                      placeholder="موقعیت ثبت نشده"
                      label="انتخاب از روی نقشه (اختیاری)"
                    />
                    <div className="text-center text-sm text-gray-500 dark:text-gray-400">یا</div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <InputWithIcon
                        icon={CrmIcon}
                        id="destination_country"
                        placeholder="مثال: ایران"
                        label="کشور (اختیاری)"
                        value={deliveryCountry}
                        onChange={e => setDeliveryCountry(e.target.value)}
                      />
                      <InputWithIcon
                        icon={MapPinIcon}
                        id="destination_city"
                        placeholder="مثال: تهران"
                        label="شهر (اختیاری)"
                        value={deliveryCity}
                        onChange={e => setDeliveryCity(e.target.value)}
                      />
                    </div>
                    <InputWithIcon
                      icon={HomeIcon}
                      id="destination_address"
                      placeholder="آدرس کامل، پلاک و واحد"
                      label="آدرس دستی (اختیاری)"
                      value={deliveryAddress}
                      onChange={e => setDeliveryAddress(e.target.value)}
                    />
                  </div>
                </div>
              </div>
              <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
                <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                  ۳. قیمت‌گذاری و اطلاعات تماس
                </h3>
                <div className="mt-6 space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <InputWithIcon
                      icon={DollarSignIcon}
                      id="item_price"
                      placeholder="مثال: 5000000"
                      label="قیمت کالا *"
                      type="number"
                      value={itemPrice}
                      onChange={e => setItemPrice(e.target.value ? Number(e.target.value) : '')}
                      required
                    />
                    <InputWithIcon
                      icon={DollarSignIcon}
                      id="proposed_fee"
                      placeholder="مثال: 200000"
                      label="هزینه پیشنهادی انجام *"
                      type="number"
                      value={proposedFee}
                      onChange={e => setProposedFee(e.target.value ? Number(e.target.value) : '')}
                      required
                    />
                  </div>
                  <SelectWithIcon
                    id="currency"
                    icon={DollarSignIcon}
                    label="واحد پولی *"
                    value={currency}
                    onChange={e => setCurrency(e.target.value as Currency)}
                  >
                    {currencies.map(({ value, label }) => (
                      <option key={value} value={value}>{label}</option>
                    ))}
                  </SelectWithIcon>
                  <div className="flex items-center justify-between bg-custom-light-bg dark:bg-custom-dark-blue p-4 rounded-lg">
                    <div className="flex items-center">
                      <PhoneIcon className="w-5 h-5 text-gray-500 dark:text-gray-400 ml-3" />
                      <div>
                        <p className="font-medium text-gray-800 dark:text-gray-200">نمایش شماره تماس</p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">برای هماهنگی شماره شما نمایش داده شود؟</p>
                      </div>
                    </div>
                    <ToggleSwitch enabled={showPhoneNumber} setEnabled={setShowPhoneNumber} />
                  </div>
                </div>
              </div>
              <button
                type="submit"
                disabled={loading}
                className="w-full bg-custom-purple hover:bg-custom-light-purple disabled:bg-gray-400 text-white font-bold py-3 px-4 rounded-lg transition-colors duration-300 shadow-lg hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-custom-purple/50"
              >
                {loading ? 'در حال ثبت...' : 'ثبت درخواست خرید'}
              </button>
            </form>
          </div>
        </div>
      ) : (
        <div className="w-full max-w-4xl mx-auto">
          <form className="space-y-8" onSubmit={handleSubmitShopper}>
            {/* 1. عنوان خدمات */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
              <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                ۱. عنوان خدمات شما
              </h3>
              <InputWithIcon
                icon={TypeIcon}
                id="service_title"
                label="عنوان خدمات (اختیاری)"
                placeholder="مثال: خرید از آمازون، خرید لپ‌تاپ و موبایل"
                value={serviceTitle}
                onChange={e => setServiceTitle(e.target.value)}
              />
            </div>
            {/* 2. دسته‌بندی */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
              <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                ۲. دسته‌بندی کالاهای قابل خرید
              </h3>
              <div className="mt-4">
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">دسته‌بندی‌هایی که می‌توانید از آن‌ها خرید کنید را انتخاب نمایید:</p>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                  {categoryOptions.map(cat => (
                    <label
                      key={cat.value}
                      className={`flex items-center justify-between p-4 border rounded-lg cursor-pointer transition-all duration-200 ${
                        categories.includes(cat.value)
                          ? 'bg-custom-purple/10 border-custom-purple ring-2 ring-custom-purple/50 dark:bg-custom-purple/20'
                          : 'bg-custom-light-bg dark:bg-custom-dark-blue border-gray-300 dark:border-gray-600 hover:border-custom-purple/50'
                      }`}
                    >
                      <span
                        className={`font-semibold transition-colors ${
                          categories.includes(cat.value)
                            ? 'text-custom-purple dark:text-custom-light-purple'
                            : 'text-gray-800 dark:text-gray-200'
                        }`}
                      >
                        {cat.label}
                      </span>
                      <input
                        type="checkbox"
                        checked={categories.includes(cat.value)}
                        onChange={e => {
                          if (e.target.checked) {
                            setCategories(prev => [...prev, cat.value]);
                          } else {
                            setCategories(prev => prev.filter(c => c !== cat.value));
                          }
                        }}
                        className="sr-only"
                      />
                      {categories.includes(cat.value) && (
                        <CheckIcon className="w-5 h-5 text-custom-purple" />
                      )}
                    </label>
                  ))}
                </div>
              </div>
            </div>
            {/* 3. سایت‌های پشتیبانی‌شده */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
              <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                ۳. سایت‌هایی که می‌توانید از آن‌ها خرید کنید
              </h3>
              <div className="mt-4">
                <InputWithIcon
                  icon={LinkIcon}
                  id="supported_sites"
                  label="سایت‌ها (با کاما جدا کنید)"
                  placeholder="مثال: amazon.com, aliexpress.com, ebay.com"
                  value={supportedSites.join(', ')}
                  onChange={e => {
                    const input = e.target.value;
                    const sites = input
                      .split(',')
                      .map(s => s.trim())
                      .filter(s => s.length > 0);
                    setSupportedSites(sites);
                  }}
                />
                <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
                  نام دامنه سایت‌ها را با کاما جدا کنید. (اختیاری)
                </p>
              </div>
            </div>
            {/* 4. محل فعالیت */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
              <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                ۴. محل فعالیت شما
              </h3>
              <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                <InputWithIcon
                  icon={CrmIcon}
                  id="shopper_country"
                  placeholder="مثال: آمریکا"
                  label="کشور *"
                  value={shopperCountry}
                  onChange={e => setShopperCountry(e.target.value)}
                  required
                />
                <InputWithIcon
                  icon={MapPinIcon}
                  id="shopper_city"
                  placeholder="مثال: نیویورک"
                  label="شهر *"
                  value={shopperCity}
                  onChange={e => setShopperCity(e.target.value)}
                  required
                />
              </div>
            </div>
            {/* 5. تصویر (اختیاری) */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
              <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                ۵. تصویر (اختیاری)
              </h3>
              <div className="space-y-6">
                <label
                  htmlFor="file-upload-shopper"
                  className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer bg-custom-light-bg dark:bg-custom-dark-blue hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                  onDrop={(e) => onDrop(e, 'shopper')}
                  onDragOver={onDragOver}
                >
                  <div className="flex flex-col items-center justify-center pt-5 pb-6">
                    <UploadCloudIcon className="w-10 h-10 mb-3 text-gray-400" />
                    <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
                      <span className="font-semibold">آپلود عکس</span> (اختیاری)
                    </p>
                    <p className="text-xs text-gray-400">فرمت‌های مجاز: JPG, PNG, GIF</p>
                  </div>
                  <input
                    id="file-upload-shopper"
                    type="file"
                    className="hidden"
                    multiple
                    accept="image/jpeg,image/png,image/gif"
                    onChange={(e) => handleImageUpload(e, 'shopper')}
                  />
                </label>
                {shopperImages.length > 0 && (
                  <div className="pt-4">
                    <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">پیش‌نمایش ({shopperImages.length} تصویر):</h4>
                    <div className="grid grid-cols-3 gap-4">
                      {shopperImages.map(image => (
                        <div key={image.id} className="relative group">
                          <img
                            src={image.url}
                            alt="Preview"
                            className="w-full h-24 object-cover rounded-md"
                          />
                          <button
                            type="button"
                            onClick={() => removeImage(image.id, 'shopper')}
                            className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                          >
                            <XIcon className="w-4 h-4" />
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
            {/* 6. جزئیات خدمات */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
              <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                ۶. جزئیات خدمات
              </h3>
              <div className="mt-6 space-y-6">
                <TextareaWithIcon
                  icon={DollarSignIcon}
                  id="fee_description"
                  label="توضیحات کارمزد (اختیاری)"
                  placeholder="نحوه محاسبه کارمزد خود را توضیح دهید (مثلاً: درصدی از قیمت کالا، مبلغ ثابت و...)"
                  value={feeDescription}
                  onChange={e => setFeeDescription(e.target.value)}
                />
                <TextareaWithIcon
                  icon={ListIcon}
                  id="capabilities"
                  label="توضیحات بیشتر (اختیاری)"
                  placeholder="اطلاعات بیشتر در مورد خدماتی که ارائه می‌دهید، تجربیات قبلی، شرایط خاص و..."
                  value={capabilities}
                  onChange={e => setCapabilities(e.target.value)}
                />
              </div>
            </div>
            {/* 7. اطلاعات تماس */}
            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-8 rounded-2xl shadow-sm">
              <h3 className="text-xl font-semibold mb-6 border-b border-gray-200 dark:border-gray-700 pb-4">
                ۷. اطلاعات تماس
              </h3>
              <div className="mt-6">
                <div className="flex items-center justify-between bg-custom-light-bg dark:bg-custom-dark-blue p-4 rounded-lg">
                  <div className="flex items-center">
                    <PhoneIcon className="w-5 h-5 text-gray-500 dark:text-gray-400 ml-3" />
                    <div>
                      <p className="font-medium text-gray-800 dark:text-gray-200">نمایش شماره تماس</p>
                      <p className="text-xs text-gray-500 dark:text-gray-400">برای هماهنگی شماره شما نمایش داده شود؟</p>
                    </div>
                  </div>
                  <ToggleSwitch enabled={showPhoneNumber} setEnabled={setShowPhoneNumber} />
                </div>
              </div>
            </div>
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-custom-purple hover:bg-custom-light-purple disabled:bg-gray-400 text-white font-bold py-3 px-4 rounded-lg transition-colors duration-300 shadow-lg hover:shadow-xl focus:outline-none focus:ring-4 focus:ring-custom-purple/50"
            >
              {loading ? 'در حال ثبت...' : 'ثبت آمادگی برای خرید'}
            </button>
          </form>
        </div>
      )}
      <LocationModal
        isOpen={modalState.isOpen}
        onClose={closeModal}
        onConfirm={confirmLocation}
        field={modalState.field}
      />
    </div>
  );
};

// ================== Helper Components ==================
interface InputWithIconProps {
  id: string;
  icon?: React.FC<{ className?: string }>;
  label: string;
  placeholder: string;
  type?: string;
  value?: string | number;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  min?: string;
  step?: string;
  required?: boolean;
}

const InputWithIcon: React.FC<InputWithIconProps> = ({
  id,
  icon: Icon,
  label,
  placeholder,
  type = 'text',
  value,
  onChange,
  min,
  step,
  required = false
}) => (
  <div>
    <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
      {label}
    </label>
    <div className="relative">
      {Icon && (
        <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
          <Icon className="w-5 h-5 text-gray-400" />
        </div>
      )}
      <input
        type={type}
        id={id}
        className={`w-full ${Icon ? 'pr-10' : 'pr-4'} pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition`}
        placeholder={placeholder}
        value={value}
        onChange={onChange}
        min={min}
        step={step}
        required={required}
      />
    </div>
  </div>
);

interface TextareaWithIconProps {
  id: string;
  icon: React.FC<{ className?: string }>;
  label: string;
  placeholder: string;
  value?: string;
  onChange?: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
}

const TextareaWithIcon: React.FC<TextareaWithIconProps> = ({ id, icon: Icon, label, placeholder, value, onChange }) => (
  <div>
    <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
    <div className="relative">
      <div className="absolute top-3.5 right-0 flex items-center pr-3 pointer-events-none">
        <Icon className="w-5 h-5 text-gray-400" />
      </div>
      <textarea
        id={id}
        className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition min-h-[100px] resize-y"
        placeholder={placeholder}
        value={value}
        onChange={onChange}
      />
    </div>
  </div>
);

interface SelectWithIconProps {
  id: string;
  icon: React.FC<{ className?: string }>;
  label: string;
  children: React.ReactNode;
  value?: string;
  onChange?: (e: React.ChangeEvent<HTMLSelectElement>) => void;
}

const SelectWithIcon: React.FC<SelectWithIconProps> = ({ id, icon: Icon, label, children, value, onChange }) => (
  <div>
    <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
    <div className="relative">
      <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
        <Icon className="w-5 h-5 text-gray-400" />
      </div>
      <select
        id={id}
        className="w-full appearance-none pr-10 pl-10 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
        value={value}
        onChange={onChange}
      >
        {children}
      </select>
      <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
        <ChevronDownIcon className="w-5 h-5 text-gray-400" />
      </div>
    </div>
  </div>
);

interface InputWithLocationButtonProps {
  id: string;
  label: string;
  placeholder: string;
  value: string;
  onButtonClick: () => void;
}

const InputWithLocationButton: React.FC<InputWithLocationButtonProps> = ({ id, label, placeholder, value, onButtonClick }) => (
  <div>
    <label htmlFor={id} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{label}</label>
    <div className="relative flex items-center">
      <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
        <MapPinIcon className="w-5 h-5 text-gray-400" />
      </div>
      <input
        type="text"
        id={id}
        className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
        placeholder={placeholder}
        value={value}
        readOnly
        onClick={onButtonClick}
        style={{ cursor: 'pointer' }}
      />
      <button
        type="button"
        onClick={onButtonClick}
        className="absolute left-2 text-sm bg-custom-purple text-white px-3 py-1 rounded-md hover:bg-custom-light-purple transition-colors"
      >
        انتخاب
      </button>
    </div>
  </div>
);

interface ToggleSwitchProps {
  enabled: boolean;
  setEnabled: (enabled: boolean) => void;
}

const ToggleSwitch: React.FC<ToggleSwitchProps> = ({ enabled, setEnabled }) => {
  return (
    <button
      type="button"
      dir="ltr"
      className={`${enabled ? 'bg-custom-purple' : 'bg-gray-200 dark:bg-gray-600'}
relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent
transition-colors duration-200 ease-in-out
focus:outline-none focus:ring-2 focus:ring-custom-purple focus:ring-offset-2`}
      onClick={() => setEnabled(!enabled)}
    >
      <span
        aria-hidden="true"
        className={`${enabled ? 'translate-x-5' : 'translate-x-0'}
pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white
shadow-lg ring-0 transition duration-200 ease-in-out`}
      />
    </button>
  );
};

// LocationModal component
interface LocationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (location: { lat: number, lng: number }) => void;
  field: LocationField | null;
}

const LocationModal: React.FC<LocationModalProps> = ({ isOpen, onClose, onConfirm, field }) => {
  const mapRef = useRef<any>(null);
  const markerRef = useRef<any>(null);
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const [selectedLocation, setSelectedLocation] = useState<{ lat: number, lng: number } | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearching, setIsSearching] = useState(false);

  useEffect(() => {
    if (!isOpen) return;
    const cleanup = () => {
      if (mapRef.current) {
        mapRef.current.remove();
        mapRef.current = null;
      }
      markerRef.current = null;
      setSelectedLocation(null);
      setSearchQuery('');
    };
    if (mapContainerRef.current && !mapRef.current) {
      const map = L.map(mapContainerRef.current).setView([35.6892, 51.3890], 10);
      mapRef.current = map;
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      }).addTo(map);
      map.on('click', (e: any) => {
        const { lat, lng } = e.latlng;
        setSelectedLocation({ lat, lng });
        if (markerRef.current) {
          markerRef.current.setLatLng(e.latlng);
        } else {
          markerRef.current = L.marker(e.latlng).addTo(mapRef.current);
        }
      });
      setTimeout(() => map.invalidateSize(), 100);
    }
    return cleanup;
  }, [isOpen]);

  const handleSearch = async () => {
    if (!searchQuery.trim()) return;
    setIsSearching(true);
    try {
      const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(searchQuery)}&accept-language=fa`);
      if (!response.ok) throw new Error('Network response was not ok');
      const data = await response.json();
      if (data && data.length > 0) {
        const { lat, lon } = data[0];
        const newLat = parseFloat(lat);
        const newLng = parseFloat(lon);
        const latlng = { lat: newLat, lng: newLng };
        setSelectedLocation(latlng);
        if (mapRef.current) {
          mapRef.current.setView(latlng, 15);
          if (markerRef.current) {
            markerRef.current.setLatLng(latlng);
          } else {
            markerRef.current = L.marker(latlng).addTo(mapRef.current);
          }
        }
      } else {
        alert('مکان مورد نظر یافت نشد.');
      }
    } catch (error) {
      console.error("Geocoding error:", error);
      alert('خطایی در جستجوی مکان رخ داد.');
    } finally {
      setIsSearching(false);
    }
  };

  const handleUseCurrentLocation = async () => {
    if (!navigator.geolocation) {
      alert("مرورگر شما از موقعیت‌یابی جغرافیایی پشتیبانی نمی‌کند.");
      return;
    }
    if (navigator.permissions && navigator.permissions.query) {
      try {
        const permissionStatus = await navigator.permissions.query({ name: 'geolocation' });
        if (permissionStatus.state === 'denied') {
          alert("شما دسترسی به موقعیت مکانی را مسدود کرده‌اید. لطفاً آن را در تنظیمات مرورگر خود فعال کنید.");
          return;
        }
      } catch (error) {
        console.warn("Could not check permission status:", error);
      }
    }
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude: lat, longitude: lng } = position.coords;
        const latlng = { lat, lng };
        setSelectedLocation(latlng);
        if (mapRef.current) {
          mapRef.current.setView(latlng, 15);
          if (markerRef.current) {
            markerRef.current.setLatLng(latlng);
          } else {
            markerRef.current = L.marker(latlng).addTo(mapRef.current);
          }
        }
      },
      (error) => {
        console.error("Geolocation error:", error.message);
        let message = "امکان دسترسی به موقعیت مکانی شما وجود ندارد.";
        switch (error.code) {
          case error.PERMISSION_DENIED:
            message = "شما اجازه دسترسی به موقعیت مکانی را نداده‌اید. لطفاً دسترسی را از تنظیمات مرورگر خود فعال کنید.";
            break;
          case error.POSITION_UNAVAILABLE:
            message = "اطلاعات موقعیت مکانی در دسترس نیست.";
            break;
          case error.TIMEOUT:
            message = "درخواست برای دریافت موقعیت مکانی بیش از حد طول کشید.";
            break;
        }
        alert(message);
      }
    );
  };

  const handleConfirm = () => {
    if (selectedLocation) {
      onConfirm(selectedLocation);
    }
  };

  if (!isOpen) return null;
  const title = 'ثبت موقعیت تحویل';
  return (
    <div
      className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4 backdrop-blur-sm"
      onClick={onClose}
    >
      <div
        className="bg-custom-light-card dark:bg-custom-dark-blue-light w-full max-w-2xl rounded-2xl shadow-2xl border border-gray-200 dark:border-gray-700/50 transform transition-all duration-300 ease-out scale-95 opacity-0 animate-fade-in-scale overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex justify-between items-center p-5 bg-custom-light-bg dark:bg-custom-dark-blue">
          <h2 className="text-xl font-bold flex items-center gap-3"><MapPinIcon className="w-6 h-6 text-custom-purple" /> {title}</h2>
          <button onClick={onClose} className="p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors">
            <XIcon className="w-6 h-6 text-gray-500 dark:text-gray-400" />
          </button>
        </div>
        <div className="p-6 space-y-5">
          <div className="flex items-center gap-2">
            <div className="relative flex-grow">
              <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                <SearchIcon className="w-5 h-5 text-gray-400" />
              </div>
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') handleSearch(); }}
                placeholder="جستجوی آدرس یا مکان..."
                className="w-full pr-10 pl-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-custom-light-bg dark:bg-custom-dark-blue focus:ring-2 focus:ring-custom-purple focus:border-transparent outline-none transition"
              />
            </div>
            <button
              onClick={handleSearch}
              disabled={isSearching}
              className="flex-shrink-0 flex items-center justify-center w-28 py-2.5 px-4 rounded-lg bg-custom-purple text-white font-semibold hover:bg-custom-light-purple transition-colors disabled:bg-gray-400 disabled:cursor-wait"
            >
              {isSearching ? (
                <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
              ) : (
                <span>جستجو</span>
              )}
            </button>
          </div>
          <button
            onClick={handleUseCurrentLocation}
            className="w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl bg-gradient-to-br from-custom-cyan to-teal-400 text-white font-semibold hover:shadow-lg hover:shadow-custom-cyan/30 transition-all duration-300 transform hover:-translate-y-0.5"
          >
            <CrosshairIcon className="w-5 h-5" />
            <span>استفاده از موقعیت فعلی من</span>
          </button>
          <div className="relative my-4">
            <div className="absolute inset-0 flex items-center" aria-hidden="true">
              <div className="w-full border-t border-gray-300 dark:border-gray-600" />
            </div>
            <div className="relative flex justify-center">
              <span className="bg-custom-light-card dark:bg-custom-dark-blue-light px-3 text-sm text-gray-500 dark:text-gray-400">یا</span>
            </div>
          </div>
          <p className="text-center text-sm text-gray-500 dark:text-gray-400 -mt-2 mb-2">برای انتخاب، روی نقشه کلیک کنید.</p>
          <div ref={mapContainerRef} className="w-full h-80 bg-gray-200 dark:bg-gray-700 rounded-lg cursor-pointer z-0 border border-gray-300 dark:border-gray-600 shadow-inner">
          </div>
          <div className="px-6 py-4 bg-custom-light-bg dark:bg-custom-dark-blue border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
            <button
              onClick={onClose}
              className="py-2 px-5 rounded-lg text-gray-700 dark:text-gray-300 font-semibold hover:bg-gray-200 dark:hover:bg-gray-700/50 transition-colors"
            >
              انصراف
            </button>
            <button
              onClick={handleConfirm}
              disabled={!selectedLocation}
              className="py-2.5 px-6 rounded-xl bg-gradient-to-br from-custom-purple to-custom-light-purple text-white font-semibold hover:shadow-lg hover:shadow-custom-purple/30 transition-all duration-300 disabled:from-gray-400 disabled:to-gray-500 disabled:shadow-none disabled:cursor-not-allowed transform disabled:transform-none hover:-translate-y-0.5"
            >
              تایید موقعیت
            </button>
          </div>
        </div>
        <style>{`
@keyframes fade-in-scale {
from { transform: scale(0.95); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
.animate-fade-in-scale {
animation: fade-in-scale 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.leaflet-container {
font-family: 'Vazirmatn', sans-serif;
}
`}</style>
      </div>
    </div>
  );
};

export default RegisterOnlinePurchasePage;