'use client';

import { useGetAddresses } from '@/app/[name]/(Profile)/profile/address/hooks/useAddressData';
import { Address } from '@/app/[name]/(Profile)/profile/address/types/Types';
import PrimaryButton from '@/components/button/PrimaryButton';
import { ChevronLeft } from 'lucide-react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useCheckoutStore } from '../../store/Store';
import useToggle from '@/hooks/helpers/useToggle';
import { AddressSelectionModal } from './AddressSelectionModal';

const formatAddress = (address: Address) => {
    return `${address.address}، ${address.city}، ${address.province}`;
};

export const AddressSection = () => {

    const { setIsSelectedAddress, selectedAddressId, setSelectedAddressId, isSelectedShipment } = useCheckoutStore();
    const params = useParams<{ name: string; id: string }>();
    const { t } = useTranslation('parallels', { keyPrefix: 'OrderDetail' });
    const { data: addressesResponse, isLoading } = useGetAddresses();
    const addresses = useMemo(() => addressesResponse?.data || [], [addressesResponse?.data]);
    const redirectUrl = `/${params.name}/order/checkout/${params.id}`;
    const { state: modalVisible, toggle: toggleModal, set: setModalVisible } = useToggle(false);

    // اگر آدرس پیش‌فرض وجود داشت، آن را تنظیم کن، در غیر این صورت آدرس اول غیر پیش‌فرض
    // در صورتی که روش تحویل انتخاب شده بود آدرس رو ست کنه
    useEffect(() => {
        if (!isLoading && addresses.length > 0 && !selectedAddressId && isSelectedShipment) {
            const defaultAddress = addresses.find(addr => addr.isDefault);
            const addressToSet = defaultAddress || addresses.filter(addr => !addr.isDefault)[0];
            if (addressToSet) {
                setIsSelectedAddress(true);
                setSelectedAddressId(addressToSet.id);
            }
        }
    }, [isLoading, addresses, setIsSelectedAddress, selectedAddressId, setSelectedAddressId, isSelectedShipment]);

    const handleSelectAddress = (addressId: string) => {
        setIsSelectedAddress(true);
        setSelectedAddressId(addressId);
        setModalVisible(false);
    };

    // پیدا کردن آدرس انتخاب شده یا آدرس پیش‌فرض یا اولین آدرس غیر پیش‌فرض
    const selectedAddress = useMemo(() => {
        if (!addresses.length) return null;
        if (selectedAddressId) {
            return addresses.find(addr => addr.id === selectedAddressId);
        }
        const defaultAddress = addresses.find(addr => addr.isDefault);
        if (defaultAddress) {
            return defaultAddress;
        }
        return addresses.filter(addr => !addr.isDefault)[0];
    }, [addresses, selectedAddressId]);

    // اگر در حال بارگذاری است، چیزی نمایش نده
    if (isLoading) {
        return null;
    }

    // اگر آدرس ندارد
    if (addresses.length === 0) {
        return (
            <section className="bg-container rounded-container box-shadow-normal p-4">
                <div className="py-3">
                    <h3 className="text-sm2 font-medium leading-5 mb-4">{t("SectionAddress.Title")}</h3>
                    <p className='text-sm2 text-disabled-text mb-4'>
                        آدرسی ثبت نشده است
                    </p>
                    <Link href={`/${params.name}/profile/address/new?redirect=${encodeURIComponent(redirectUrl)}`}>
                        <PrimaryButton>
                            افزودن آدرس جدید
                        </PrimaryButton>
                    </Link>
                </div>
            </section>
        );
    }

    // اگر آدرس انتخاب شده وجود ندارد، نمایش نده
    // if (!selectedAddress) {
    //     return null;
    // }

    return (
        <>
            <section className="bg-container rounded-container box-shadow-normal p-4">
                <div className="py-3">
                    <div className='w-full flex justify-between items-center gap-2'>
                        <h3 className="text-sm2 font-medium leading-5 inline-block">{t("SectionAddress.Title")}</h3>
                        <button
                            onClick={toggleModal}
                            className='text-sm2 text-primary dark:text-foreground cursor-pointer'
                        >
                            {t("SectionAddress.ButtonChangeAddress")}
                            <ChevronLeft className='inline-block mr-1 mb-0.5 stroke-primary dark:stroke-foreground' size='16' />
                        </button>
                    </div>
                    <p className='mt-6 text-sm2'>
                        <div className='font-bold'>
                            {selectedAddress?.title}
                        </div>
                        {selectedAddress && formatAddress(selectedAddress)}
                    </p>
                </div>
            </section>

            <AddressSelectionModal
                visible={modalVisible}
                addresses={addresses}
                redirectUrl={redirectUrl}
                name={params.name}
                selectedAddressId={selectedAddressId}
                onClose={() => setModalVisible(false)}
                onSelectAddress={handleSelectAddress}
            />
        </>
    );
};

