// src/components/pages/PurchaseDetailPage.tsx
import React, { useState, useEffect } from 'react';
import {
    PencilIcon,
    Trash2Icon,
    MapPinIcon,
    HomeIcon,
    DollarSignIcon,
    PackageIcon,
    LinkIcon,
    PhoneIcon,
    ImageIcon,
    XIcon,
    TypeIcon,
    ListIcon,
    UploadCloudIcon,
    ArrowLeftIcon,
    ChevronDownIcon,
    GlobeIcon,
    TruckIcon,
    InfoIcon,
    UserIcon,
    ShoppingBagIcon,
    CheckIcon
} from 'lucide-react';
import { authFetch } from '../../App';
import { API_BASE_URL } from '@/src/config.js';
// --- Helper Components ---
const InputWithIcon = ({ 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>
);

const TextareaWithIcon = ({ 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>
);

const SelectWithIcon = ({ 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>
);

const ToggleSwitch = ({ enabled, setEnabled }) => (
    <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>
);

// === Constants ===
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: 'سایر' },
];

// === Helper: Parse JSON fields safely ===
const parseJsonField = (field) => {
    if (Array.isArray(field)) return field;
    if (typeof field === 'string' && field.trim() !== '') {
        try {
            return JSON.parse(field);
        } catch (e) {
            console.error("Failed to parse JSON field:", field, e);
            return [];
        }
    }
    return [];
};

// === Main Component ===
const PurchaseDetailPage = ({ purchaseId, type, onNavigate, isOwnerView = false }) => {
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [data, setData] = useState(null);
    const [isEditMode, setIsEditMode] = useState(false);
    const [saving, setSaving] = useState(false);
    const [deleting, setDeleting] = useState(false);

    // === States (Request & Shopper) ===
    const [title, setTitle] = useState('');
    const [link, setLink] = useState('');
    const [description, setDescription] = useState('');
    const [deliveryLat, setDeliveryLat] = useState(null);
    const [deliveryLng, setDeliveryLng] = useState(null);
    const [deliveryCountry, setDeliveryCountry] = useState('');
    const [deliveryCity, setDeliveryCity] = useState('');
    const [deliveryAddress, setDeliveryAddress] = useState('');
    const [itemPrice, setItemPrice] = useState('');
    const [proposedFee, setProposedFee] = useState('');
    const [currency, setCurrency] = useState('IRT');
    const [showPhone, setShowPhone] = useState(false);
    const [existingImages, setExistingImages] = useState([]);
    const [deletedImageIds, setDeletedImageIds] = useState([]);
    const [newImages, setNewImages] = useState([]);
    const [serviceTitle, setServiceTitle] = useState('');
    const [categories, setCategories] = useState([]);
    const [supportedSites, setSupportedSites] = useState([]);
    const [shopperCountry, setShopperCountry] = useState('');
    const [shopperCity, setShopperCity] = useState('');
    const [feeDescription, setFeeDescription] = useState('');
    const [capabilities, setCapabilities] = useState('');
    const [shopperImages, setShopperImages] = useState([]);
    const [deletedShopperImageIds, setDeletedShopperImageIds] = useState([]);

    // === Fetch Data ===
    useEffect(() => {
        if (!purchaseId) {
            setError('شناسه نامعتبر است');
            setLoading(false);
            return;
        }
        const fetchDetail = async () => {
            try {
                setLoading(true);
                const token = localStorage.getItem('auth_token');
                const endpoint =
                    type === 'request'
                        ? `${API_BASE_URL}/online-purchase/request/${purchaseId}`
                        : `${API_BASE_URL}/online-purchase/shopper/${purchaseId}`;
                const res = await fetch(endpoint, {
                    headers: { 'X-Auth-Token': token, },
                });
                if (!res.ok) throw new Error('خطا در دریافت اطلاعات');
                const result = await res.json();
                if (!result.success || !result.data) throw new Error('داده‌ای یافت نشد');
                const item = result.data;
                setData(item);
                if (type === 'request') {
                    setTitle(item.title || '');
                    setLink(item.link || '');
                    setDescription(item.description || '');
                    setDeliveryLat(item.delivery_lat ? parseFloat(item.delivery_lat) : null);
                    setDeliveryLng(item.delivery_lng ? parseFloat(item.delivery_lng) : null);
                    setDeliveryCountry(item.delivery_country || '');
                    setDeliveryCity(item.delivery_city || '');
                    setDeliveryAddress(item.delivery_address || '');
                    setItemPrice(item.item_price ? parseFloat(item.item_price) : '');
                    setProposedFee(item.proposed_fee ? parseFloat(item.proposed_fee) : '');
                    setCurrency(item.currency || 'IRT');
                    setShowPhone(item.show_phone || false);
                    setExistingImages(item.images || []);
                } else {
                    setServiceTitle(item.service_title || '');
                    setCategories(parseJsonField(item.categories));
                    setSupportedSites(parseJsonField(item.supported_sites));
                    setShopperCountry(item.country || '');
                    setShopperCity(item.city || '');
                    setFeeDescription(item.fee_description || '');
                    setCapabilities(item.capabilities || '');
                    setShopperImages(item.images || []);
                    setShowPhone(item.show_phone || false);
                }
            } catch (err) {
                setError(err.message || 'خطای ناشناخته');
            } finally {
                setLoading(false);
            }
        };
        fetchDetail();
    }, [purchaseId, type]);

    // === Handlers ===
    const handleDelete = async () => {
        if (!confirm('آیا از حذف اطمینان دارید؟')) return;
        setDeleting(true);
        try {
            const token = localStorage.getItem('auth_token');
            const endpoint =
                type === 'request'
                    ? `${API_BASE_URL}/online-purchase/request/${purchaseId}`
                    : `${API_BASE_URL}/online-purchase/shopper/${purchaseId}`;
            const res = await fetch(endpoint, { method: 'DELETE', headers: { 'X-Auth-Token': token, } });
            const result = await res.json();
            if (result.success) {
                alert('با موفقیت حذف شد');
                onNavigate('online-purchase');
            } else {
                throw new Error(result.message || 'خطا در حذف');
            }
        } catch (err) {
            alert(err.message || 'خطا در اتصال');
        } finally {
            setDeleting(false);
        }
    };

    const handleImageUpload = (files, target) => {
        if (files) {
            const newImages = Array.from(files).map((file) => ({
                id: Date.now() + Math.random(),
                url: URL.createObjectURL(file),
                file,
            }));
            if (target === 'request') {
                setNewImages((prev) => [...prev, ...newImages]);
            } else {
                setShopperImages((prev) => [...prev, ...newImages]);
            }
        }
    };

    const removeImage = (id, target) => {
        if (target === 'request') {
            const img = existingImages.find((i) => i.id === id);
            if (img) URL.revokeObjectURL(img.url);
            setExistingImages((prev) => prev.filter((i) => i.id !== id));
            setDeletedImageIds((prev) => [...prev, id]);
        } else {
            const imgIndex = shopperImages.findIndex((i) => i.id === id);
            if (imgIndex > -1) {
                const img = shopperImages[imgIndex];
                if (img.url.startsWith('blob:')) URL.revokeObjectURL(img.url);
                const newImages = [...shopperImages];
                newImages.splice(imgIndex, 1);
                setShopperImages(newImages);
                setDeletedShopperImageIds((prev) => [...prev, id]);
            }
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            const token = localStorage.getItem('auth_token');
            const formData = new FormData();
            if (type === 'request') {
                formData.append('title', title);
                if (link) formData.append('link', link);
                if (description) formData.append('description', description);
                if (deliveryLat) formData.append('delivery_lat', String(deliveryLat));
                if (deliveryLng) formData.append('delivery_lng', String(deliveryLng));
                formData.append('delivery_country', deliveryCountry);
                formData.append('delivery_city', deliveryCity);
                formData.append('delivery_address', deliveryAddress);
                formData.append('item_price', String(itemPrice));
                formData.append('proposed_fee', String(proposedFee));
                formData.append('currency', currency);
                formData.append('show_phone', showPhone ? '1' : '0');
                deletedImageIds.forEach((id) => formData.append('deleted_images[]', String(id)));
                newImages.forEach((img) => formData.append('images[]', img.file));
            } else {
                formData.append('service_title', serviceTitle);
                formData.append('country', shopperCountry);
                formData.append('city', shopperCity);
                if (feeDescription) formData.append('fee_description', feeDescription);
                if (capabilities) formData.append('capabilities', capabilities);
                formData.append('show_phone', showPhone ? '1' : '0');
                categories.forEach((cat) => formData.append('categories[]', cat));
                supportedSites.forEach((site) => formData.append('supported_sites[]', site));
                deletedShopperImageIds.forEach((id) => formData.append('deleted_images[]', String(id)));
                shopperImages
                    .filter((img) => img.file)
                    .forEach((img) => formData.append('images[]', img.file));
            }
            formData.append('_method', 'PUT');
            const endpoint =
                type === 'request'
                    ? `${API_BASE_URL}/online-purchase/request/${purchaseId}`
                    : `${API_BASE_URL}/online-purchase/shopper/${purchaseId}`;
            const res = await fetch(endpoint, {
                method: 'POST',
                headers: { 'X-Auth-Token': token, },
                body: formData,
            });
            const result = await res.json();
            if (result.success) {
                alert('تغییرات با موفقیت ذخیره شد');
                setIsEditMode(false);
                const updatedItem = result.data;
                setData(updatedItem);
                if (type === 'request') {
                    setTitle(updatedItem.title || '');
                    setLink(updatedItem.link || '');
                    setDescription(updatedItem.description || '');
                    setDeliveryLat(updatedItem.delivery_lat ? parseFloat(updatedItem.delivery_lat) : null);
                    setDeliveryLng(updatedItem.delivery_lng ? parseFloat(updatedItem.delivery_lng) : null);
                    setDeliveryCountry(updatedItem.delivery_country || '');
                    setDeliveryCity(updatedItem.delivery_city || '');
                    setDeliveryAddress(updatedItem.delivery_address || '');
                    setItemPrice(updatedItem.item_price ? parseFloat(updatedItem.item_price) : '');
                    setProposedFee(updatedItem.proposed_fee ? parseFloat(updatedItem.proposed_fee) : '');
                    setCurrency(updatedItem.currency || 'IRT');
                    setShowPhone(updatedItem.show_phone || false);
                    setExistingImages(updatedItem.images || []);
                    setNewImages([]);
                    setDeletedImageIds([]);
                } else {
                    setServiceTitle(updatedItem.service_title || '');
                    setCategories(parseJsonField(updatedItem.categories));
                    setSupportedSites(parseJsonField(updatedItem.supported_sites));
                    setShopperCountry(updatedItem.country || '');
                    setShopperCity(updatedItem.city || '');
                    setFeeDescription(updatedItem.fee_description || '');
                    setCapabilities(updatedItem.capabilities || '');
                    setShopperImages(updatedItem.images || []);
                    setShowPhone(updatedItem.show_phone || false);
                    setDeletedShopperImageIds([]);
                }
            } else {
                throw new Error(result.message || 'خطا در ذخیره');
            }
        } catch (err) {
            alert(err.message || 'خطا در ارسال');
        } finally {
            setSaving(false);
        }
    };

    // === Render Loading / Error ===
    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="w-12 h-12 border-4 border-custom-purple border-t-transparent rounded-full animate-spin" />
            </div>
        );
    }
    if (error || !data) {
        return (
            <div className="text-center py-12">
                <p className="text-red-500 mb-4">{error || 'اطلاعات یافت نشد'}</p>
                <button
                    onClick={() => onNavigate('online-purchase')}
                    className="flex items-center gap-2 text-custom-purple hover:underline"
                >
                    <ArrowLeftIcon className="w-4 h-4" /> بازگشت
                </button>
            </div>
        );
    }

    const item = data;

    // === Edit Mode: Request ===
    if (isEditMode && type === 'request') {
        return (
            <form onSubmit={handleSubmit} className="space-y-8">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <h1 className="text-3xl font-bold text-gray-800 dark:text-white">ویرایش درخواست خرید</h1>
                    <button
                        type="button"
                        onClick={() => setIsEditMode(false)}
                        className="flex items-center gap-2 py-2 px-4 rounded-lg text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-custom-dark-blue transition-colors"
                    >
                        <span>بازگشت به نمایش</span>
                    </button>
                </div>
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div className="lg:col-span-1 space-y-6">
                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                            <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-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"
                            >
                                <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.target.files, 'request')}
                                />
                            </label>
                        </div>
                        {(existingImages.length > 0 || newImages.length > 0) && (
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4">پیش‌نمایش ({(existingImages.length + newImages.length)} تصویر)</h3>
                                <div className="grid grid-cols-2 gap-4">
                                    {existingImages.map((img) => (
                                        <div key={img.id} className="relative group">
                                            <img src={`${img.url}`} alt="تصویر" className="w-full h-24 object-cover rounded-md" />
                                            <button
                                                type="button"
                                                onClick={() => removeImage(img.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>
                                    ))}
                                    {newImages.map((img, idx) => (
                                        <div key={`new-${idx}`} className="relative group">
                                            <img src={img.url} alt="جدید" className="w-full h-24 object-cover rounded-md" />
                                            <button
                                                type="button"
                                                onClick={() => setNewImages((prev) => prev.filter((_, i) => i !== idx))}
                                                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 space-y-8">
                        <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">
                                <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="space-y-4">
                                <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>
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        <InputWithIcon
                                            icon={GlobeIcon}
                                            id="delivery_country"
                                            placeholder="مثال: ایران"
                                            label="کشور (اختیاری)"
                                            value={deliveryCountry}
                                            onChange={(e) => setDeliveryCountry(e.target.value)}
                                        />
                                        <InputWithIcon
                                            icon={MapPinIcon}
                                            id="delivery_city"
                                            placeholder="مثال: تهران"
                                            label="شهر (اختیاری)"
                                            value={deliveryCity}
                                            onChange={(e) => setDeliveryCity(e.target.value)}
                                        />
                                    </div>
                                    <InputWithIcon
                                        icon={HomeIcon}
                                        id="delivery_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="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"
                                        min="0"
                                        step="1000"
                                        value={itemPrice}
                                        onChange={(e) => setItemPrice(e.target.value)}
                                        required
                                    />
                                    <InputWithIcon
                                        icon={DollarSignIcon}
                                        id="proposed_fee"
                                        placeholder="مثال: 200000"
                                        label="هزینه پیشنهادی *"
                                        type="number"
                                        min="0"
                                        step="1000"
                                        value={proposedFee}
                                        onChange={(e) => setProposedFee(e.target.value)}
                                        required
                                    />
                                </div>
                                <SelectWithIcon
                                    id="currency"
                                    icon={DollarSignIcon}
                                    label="واحد پولی *"
                                    value={currency}
                                    onChange={(e) => setCurrency(e.target.value)}
                                >
                                    {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={showPhone} setEnabled={setShowPhone} />
                                </div>
                            </div>
                        </div>
                        <div className="flex justify-end gap-4">
                            <button
                                type="button"
                                onClick={() => setIsEditMode(false)}
                                disabled={saving}
                                className="px-6 py-3 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 font-bold rounded-lg transition-colors duration-300 disabled:opacity-50"
                            >
                                لغو
                            </button>
                            <button
                                type="submit"
                                disabled={saving}
                                className="px-6 py-3 bg-custom-purple hover:bg-custom-light-purple text-white font-bold rounded-xl transition-colors shadow-lg hover:shadow-xl disabled:opacity-50 flex items-center gap-2"
                            >
                                {saving && <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>}
                                ذخیره تغییرات
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        );
    }

    // === Edit Mode: Shopper ===
    if (isEditMode && type === 'shopper') {
        return (
            <form onSubmit={handleSubmit} className="space-y-8">
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <h1 className="text-3xl font-bold text-gray-800 dark:text-white">ویرایش پروفایل خریدار</h1>
                    <button
                        type="button"
                        onClick={() => setIsEditMode(false)}
                        className="flex items-center gap-2 py-2 px-4 rounded-lg text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-custom-dark-blue transition-colors"
                    >
                        <span>بازگشت به نمایش</span>
                    </button>
                </div>
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div className="lg:col-span-1 space-y-6">
                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                            <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4">تصویر (اختیاری)</h3>
                            <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"
                            >
                                <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.target.files, 'shopper')}
                                />
                            </label>
                        </div>
                        {(shopperImages.length > 0) && (
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4">پیش‌نمایش ({shopperImages.length} تصویر)</h3>
                                <div className="grid grid-cols-3 gap-4">
                                    {shopperImages.map((image, idx) => (
                                        <div key={typeof image.id === 'number' ? image.id : `temp-${idx}`} 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 || `temp-${idx}`, '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 className="lg:col-span-2 space-y-8">
                        <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>
                        <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 p-3 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'
                                                }`}
                                        >
                                            <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"
                                            />
                                            <div
                                                className={`w-5 h-5 border-2 rounded flex-shrink-0 flex items-center justify-center ml-3 transition-all duration-200 ${categories.includes(cat.value)
                                                    ? 'bg-custom-purple border-custom-purple'
                                                    : 'border-gray-300 dark:border-gray-500'
                                                    }`}
                                            >
                                                {categories.includes(cat.value) && (
                                                    <svg className="w-3 h-3 text-white fill-current" viewBox="0 0 20 20">
                                                        <path d="M0 11l2-2 5 5L18 3l2 2L7 18z" />
                                                    </svg>
                                                )}
                                            </div>
                                            <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>
                                        </label>
                                    ))}
                                </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-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>
                        <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={GlobeIcon}
                                    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>
                        <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>
                        <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="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={showPhone} setEnabled={setShowPhone} />
                            </div>
                        </div>
                        <div className="flex justify-end gap-4">
                            <button
                                type="button"
                                onClick={() => setIsEditMode(false)}
                                disabled={saving}
                                className="px-6 py-3 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 font-bold rounded-lg transition-colors duration-300 disabled:opacity-50"
                            >
                                لغو
                            </button>
                            <button
                                type="submit"
                                disabled={saving}
                                className="px-6 py-3 bg-custom-purple hover:bg-custom-light-purple text-white font-bold rounded-xl transition-colors shadow-lg hover:shadow-xl disabled:opacity-50 flex items-center gap-2"
                            >
                                {saving && <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>}
                                ذخیره تغییرات
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        );
    }

    // === View Mode ===
    return (
        <div className="space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div className="flex items-center gap-4">
                   
                    <div>
                        <h1 className="text-3xl font-bold text-gray-800 dark:text-white">
                            {type === 'request' ? item.title : item.service_title || 'پروفایل خریدار'}
                        </h1>
                        <p className="text-gray-500 dark:text-gray-400 mt-1">
                            {type === 'request' ? 'جزئیات درخواست خرید آنلاین' : 'جزئیات پروفایل خریدار'}
                        </p>
                    </div>
                </div>
            </div>
            {/* --- Main Content Grid --- */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div className="lg:col-span-2 space-y-8">
                    {/* Images */}
                    {item.images && item.images.length > 0 && (
                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                            <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                <ImageIcon className="w-5 h-5 text-custom-purple" /> تصاویر
                            </h3>
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                {item.images.map((img) => (
                                    <img
                                        key={img.id}
                                        src={img.url.startsWith('http') ? img.url : `https://eino.eifa.site/users-api/public${img.url}`}
                                        alt="تصویر"
                                        className="w-full h-32 object-cover rounded-xl"
                                    />
                                ))}
                            </div>
                        </div>
                    )}
                    {/* Request View */}
                    {type === 'request' && (
                        <>
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                    <PackageIcon className="w-5 h-5 text-custom-purple" /> اطلاعات کالا
                                </h3>
                                <div className="space-y-4">
                                    <div className="flex items-start gap-3">
                                        <TypeIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                        <div>
                                            <span className="text-gray-500 dark:text-gray-400 text-sm">عنوان:</span>
                                            <p className="font-medium">{item.title}</p>
                                        </div>
                                    </div>
                                    {item.link && (
                                        <div className="flex items-start gap-3">
                                            <LinkIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                            <div>
                                                <span className="text-gray-500 dark:text-gray-400 text-sm">لینک:</span>
                                                <a href={item.link} target="_blank" rel="noopener noreferrer" className="text-custom-purple hover:underline block">
                                                    {item.link}
                                                </a>
                                            </div>
                                        </div>
                                    )}
                                    {item.description && (
                                        <div>
                                            <div className="flex items-start gap-3 mb-2">
                                                <ListIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                                <span className="text-gray-500 dark:text-gray-400 text-sm">توضیحات:</span>
                                            </div>
                                            <p className="text-gray-600 dark:text-gray-300 leading-relaxed whitespace-pre-line bg-custom-light-bg dark:bg-custom-dark-blue p-3 rounded-lg">
                                                {item.description}
                                            </p>
                                        </div>
                                    )}
                                </div>
                            </div>
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                    <DollarSignIcon className="w-5 h-5 text-custom-purple" /> قیمت‌گذاری
                                </h3>
                                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                                    <div className="bg-custom-light-bg dark:bg-custom-dark-blue p-4 rounded-xl">
                                        <span className="text-sm text-gray-500 dark:text-gray-400">قیمت کالا:</span>
                                        <p className="font-bold text-custom-purple">
                                            {parseFloat(item.item_price).toLocaleString()} {currencies.find(c => c.value === item.currency)?.label || item.currency}
                                        </p>
                                    </div>
                                    <div className="bg-custom-light-bg dark:bg-custom-dark-blue p-4 rounded-xl">
                                        <span className="text-sm text-gray-500 dark:text-gray-400">هزینه پیشنهادی:</span>
                                        <p className="font-bold text-custom-cyan">
                                            {parseFloat(item.proposed_fee).toLocaleString()} {currencies.find(c => c.value === item.currency)?.label || item.currency}
                                        </p>
                                    </div>
                                    <div className="bg-custom-light-bg dark:bg-custom-dark-blue p-4 rounded-xl">
                                        <span className="text-sm text-gray-500 dark:text-gray-400">جمع کل:</span>
                                        <p className="font-bold text-green-500">
                                            {(parseFloat(item.item_price) + parseFloat(item.proposed_fee)).toLocaleString()}{' '}
                                            {currencies.find(c => c.value === item.currency)?.label || item.currency}
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                    <TruckIcon className="w-5 h-5 text-custom-purple" /> محل تحویل
                                </h3>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div>
                                        <h4 className="font-medium text-green-600 dark:text-green-400 mb-2 flex items-center gap-2">
                                            <MapPinIcon className="w-4 h-4" /> مقصد تحویل
                                        </h4>
                                        {item.delivery_country && (
                                            <p className="text-gray-700 dark:text-gray-300 mb-1">
                                                <span className="font-semibold">{item.delivery_country}</span>
                                            </p>
                                        )}
                                        {item.delivery_city && (
                                            <p className="text-gray-600 dark:text-gray-400 text-sm">{item.delivery_city}</p>
                                        )}
                                        {item.delivery_address && (
                                            <p className="text-gray-600 dark:text-gray-400 text-sm">{item.delivery_address}</p>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </>
                    )}
                    {/* Shopper View */}
                    {type === 'shopper' && (
                        <>
                            <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                    <MapPinIcon className="w-5 h-5 text-custom-purple" /> موقعیت مکانی
                                </h3>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div>
                                        <h4 className="font-medium text-green-600 dark:text-green-400 mb-2 flex items-center gap-2">
                                            <GlobeIcon className="w-4 h-4" /> کشور
                                        </h4>
                                        <p className="text-gray-700 dark:text-gray-300 mb-1">
                                            <span className="font-semibold">{item.country}</span>
                                        </p>
                                    </div>
                                    <div>
                                        <h4 className="font-medium text-green-600 dark:text-green-400 mb-2 flex items-center gap-2">
                                            <MapPinIcon className="w-4 h-4" /> شهر
                                        </h4>
                                        <p className="text-gray-700 dark:text-gray-300 mb-1">
                                            <span className="font-semibold">{item.city}</span>
                                        </p>
                                    </div>
                                </div>
                            </div>
                            {(() => {
                                const categoriesArray = parseJsonField(item.categories);
                                return categoriesArray.length > 0 && (
                                    <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                        <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                            <ShoppingBagIcon className="w-5 h-5 text-custom-purple" /> دسته‌بندی‌ها
                                        </h3>
                                        <div className="flex flex-wrap gap-2">
                                            {categoriesArray.map((cat) => {
                                                const option = categoryOptions.find((c) => c.value === cat);
                                                return (
                                                    <span key={cat} className="px-3 py-1 bg-custom-purple/10 text-custom-purple dark:bg-custom-purple/20 dark:text-custom-light-purple rounded-full text-sm font-medium">
                                                        {option?.label || cat}
                                                    </span>
                                                );
                                            })}
                                        </div>
                                    </div>
                                );
                            })()}
                            {(() => {
                                const sitesArray = parseJsonField(item.supported_sites);
                                return sitesArray.length > 0 && (
                                    <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                        <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                            <GlobeIcon className="w-5 h-5 text-custom-purple" /> سایت‌های پشتیبانی شده
                                        </h3>
                                        <div className="flex flex-wrap gap-2">
                                            {sitesArray.map((site) => (
                                                <span key={site} className="px-3 py-1 bg-custom-purple/10 text-custom-purple dark:bg-custom-purple/20 dark:text-custom-light-purple rounded-full text-sm font-medium">
                                                    {site}
                                                </span>
                                            ))}
                                        </div>
                                    </div>
                                );
                            })()}
                            {(item.fee_description || item.capabilities) && (
                                <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                                    <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                        <InfoIcon className="w-5 h-5 text-custom-purple" /> جزئیات خدمات
                                    </h3>
                                    <div className="space-y-4">
                                        {item.fee_description && (
                                            <div>
                                                <div className="flex items-start gap-3 mb-2">
                                                    <DollarSignIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                                    <span className="text-gray-500 dark:text-gray-400 text-sm">توضیحات کارمزد:</span>
                                                </div>
                                                <p className="text-gray-600 dark:text-gray-300 leading-relaxed whitespace-pre-line bg-custom-light-bg dark:bg-custom-dark-blue p-3 rounded-lg">
                                                    {item.fee_description}
                                                </p>
                                            </div>
                                        )}
                                        {item.capabilities && (
                                            <div>
                                                <div className="flex items-start gap-3 mb-2">
                                                    <ListIcon className="w-5 h-5 text-gray-500 mt-0.5" />
                                                    <span className="text-gray-500 dark:text-gray-400 text-sm">توضیحات بیشتر:</span>
                                                </div>
                                                <p className="text-gray-600 dark:text-gray-300 leading-relaxed whitespace-pre-line bg-custom-light-bg dark:bg-custom-dark-blue p-3 rounded-lg">
                                                    {item.capabilities}
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}
                        </>
                    )}
                    {/* Contact Info Card (Common for both) */}
                    {item.show_phone && item.user?.phone && (
                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                            <h3 className="text-xl font-semibold mb-4 border-b border-gray-200 dark:border-gray-700 pb-4 flex items-center gap-2">
                                <PhoneIcon className="w-5 h-5 text-custom-purple" /> اطلاعات تماس
                            </h3>
                            <div className="flex items-center gap-4">
                                <UserIcon className="w-10 h-10 text-gray-400" />
                                <div>
                                    <p className="font-medium text-gray-800 dark:text-gray-200">{item.user.name}</p>
                                    <p className="text-custom-purple">{item.user.phone}</p>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
                {/* --- Sidebar --- */}
                {isOwnerView && (
                    <div className="lg:col-span-1 space-y-6">
                        <div className="bg-custom-light-card dark:bg-custom-dark-blue-light p-6 rounded-2xl shadow-sm">
                            <h3 className="text-lg font-semibold pb-3 border-b border-gray-200 dark:border-gray-700">عملیات</h3>
                            <div className="grid grid-cols-2 gap-4 mt-4">
                                <button
                                    onClick={() => setIsEditMode(true)}
                                    className="flex flex-col items-center justify-center gap-2 bg-custom-cyan/10 hover:bg-custom-cyan/20 text-custom-cyan font-bold py-3 px-4 rounded-lg transition-colors"
                                >
                                    <PencilIcon className="w-5 h-5" />
                                    <span className="text-sm">ویرایش</span>
                                </button>
                                <button
                                    onClick={handleDelete}
                                    disabled={deleting}
                                    className="flex flex-col items-center justify-center gap-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 font-bold py-3 px-4 rounded-lg transition-colors disabled:opacity-50"
                                >
                                    {deleting ? (
                                        <div className="w-5 h-5 border-2 border-red-500 border-t-transparent rounded-full animate-spin"></div>
                                    ) : (
                                        <Trash2Icon className="w-5 h-5" />
                                    )}
                                    <span className="text-sm">{deleting ? 'حذف...' : 'حذف'}</span>
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default PurchaseDetailPage;