import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { useTranslation } from 'next-i18next';
import { EnvironmentOutlined, UserOutlined } from '@ant-design/icons';
import { UseQueryResult, useMutation } from '@tanstack/react-query';
import { Button, DatePicker, Form, Input, Select, Spin } from 'antd';
import { useMemberContext } from '@/providers/MemberContext';
import { updateMyProfile } from '@/services/my-profile';
import { AxiosErrorResponse, Member, UpdateMemberProfileParams } from '@/types';
import { errorMessageFormatter } from '@/utils/errorFormatter';
import dayjs from 'dayjs';
import { getStates, getCities } from 'malaysia-postcodes';

interface ProfileProps {
    memberQuery: UseQueryResult<Member | null>;
}

const Profile: React.FC<ProfileProps> = ({ memberQuery }) => {
    const { t } = useTranslation(['member', 'common']);
    const { member } = useMemberContext();
    const [memberForm] = Form.useForm();
    const memberToBeEdit = memberQuery.data;

    const states = getStates();
    const [selectedState, setSelectedState] = useState<string | undefined>(undefined);
    const [cities, setCities] = useState<string[]>([]);

    useEffect(() => {
        if (selectedState) {
            if (selectedState === 'others') {
                return;
            }

            setCities(getCities(selectedState));
        }
    }, [selectedState, memberForm]);

    useEffect(() => {
        if (memberToBeEdit) {
            const { dateOfBirth, ...rest } = memberToBeEdit;

            memberForm.setFieldsValue({
                dateOfBirth: dayjs.tz(memberToBeEdit.dateOfBirth),
                ...rest,
            });

            setSelectedState(memberToBeEdit.state);
        }
    }, [memberToBeEdit]);

    // Mutation
    const updateMyProfileMutation = useMutation({
        mutationFn: async (body: UpdateMemberProfileParams) => {
            const res = await updateMyProfile(body);
            return res.data;
        },
        onSuccess: () => {
            memberQuery.refetch();
        },
    });

    // Function
    const onUpdateMemberProfileHandler = () => {
        memberForm.validateFields().then(async (values) => {
            toast.promise(updateMyProfileMutation.mutateAsync(values), {
                pending: t('messages:updating-member-profile'),
                success: t('messages:member-profile-updated'),
                error: {
                    render({ data }) {
                        return t(errorMessageFormatter(data as AxiosErrorResponse));
                    },
                },
            });
        });
    };

    return (
        <Spin spinning={updateMyProfileMutation.isLoading}>
            {member && (
                <div className="flex flex-col lg:flex-row">
                    <div className="order-2 w-full px-2 mt-10 lg:mt-0 lg:flex-1 lg:order-1">
                        <Form form={memberForm} layout="vertical" title="Member Form">
                            {/* Full name */}
                            <Form.Item
                                label={t('full-name')}
                                name="fullName"
                                rules={[
                                    {
                                        required: true,
                                    },
                                ]}
                                className="mb-5"
                                labelCol={{ flex: '35px' }}
                            >
                                <Input classNames={{ prefix: '!me-2' }} prefix={<UserOutlined className="site-form-item-icon" />} />
                            </Form.Item>
                            {/* Preferred name */}
                            <Form.Item label={t('preferred-name')} name="preferredName" className="mb-5" labelCol={{ flex: '35px' }}>
                                <Input classNames={{ prefix: '!me-2' }} prefix={<UserOutlined className="site-form-item-icon" />} />
                            </Form.Item>
                            {/* Address */}
                            <Form.Item
                                label={t('address')}
                                name="address"
                                rules={[
                                    {
                                        required: true,
                                    },
                                ]}
                                className="mb-5"
                                labelCol={{ flex: '35px' }}
                            >
                                <Input classNames={{ prefix: '!me-2' }} prefix={<EnvironmentOutlined className="site-form-item-icon" />} />
                            </Form.Item>
                            <Form.Item label={t('state')} name="state" rules={[{ required: true }]}>
                                <Select
                                    options={[
                                        ...states.map((state: string) => ({
                                            label: state,
                                            value: state,
                                        })),
                                        {
                                            label: "Others",
                                            value: "others",
                                        },
                                    ]}
                                    onChange={(value) => setSelectedState(value)}
                                />
                            </Form.Item>
                            <Form.Item label={t('city')} name="city">
                                <Select
                                    options={
                                        cities.map((city) => ({
                                            label: city,
                                            value: city,
                                        }))
                                    }
                                    disabled={!selectedState || selectedState === 'others'}
                                />
                            </Form.Item>
                            {
                                selectedState === 'others' && (
                                    <Form.Item label={t('country')} name="country" rules={[{ required: true }]}>
                                        <Input />
                                    </Form.Item>
                                )
                            }
                            {/* Date of Birth */}
                            <Form.Item
                                label={t('date-of-birth')}
                                name="dateOfBirth"
                                rules={[
                                    {
                                        required: true,
                                    },
                                ]}
                                className="mb-5"
                                labelCol={{ flex: '35px' }}
                            >
                                <DatePicker format={'DD MMM YYYY'} style={{ width: '100%' }} />
                            </Form.Item>
                            {/* Source */}
                            <Form.Item label={t('source-of-knowing-us')} name="source" className="mb-5" labelCol={{ flex: '35px' }}>
                                <Input />
                            </Form.Item>
                            <Form.Item label={t('preferred-language')} name="preferredLanguage" className="mb-5" labelCol={{ flex: '35px' }}>
                                <Select options={[{ label: 'English', value: 'en' }, { label: 'Chinese', value: 'cn' }, { label: 'Malay', value: 'bm' }]} />
                            </Form.Item>
                            <div className="flex justify-end">
                                <Button
                                    type="primary"
                                    className="hover:!text-white"
                                    style={{ transition: 'none' }}
                                    onClick={onUpdateMemberProfileHandler}
                                    loading={updateMyProfileMutation.isLoading}
                                >
                                    {t('common:update')}
                                </Button>
                            </div>
                        </Form>
                    </div>
                </div>
            )}
        </Spin>
    );
};

export default Profile;
