import LayoutWithNav from '@/components/layout/LayoutWithNav'
import { Space, Typography, Button, message, Steps, Row, Col, Form, Input, Select, InputNumber } from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import { useUser } from 'context/UserContext'
import type { NextPage } from 'next'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import { SyncLoader } from 'react-spinners'
import { getToken } from 'utilFuncs/utilFunctions'
import { useMutation, useQuery } from 'react-query';
import { classifiedById, classifiedsOnly, fetchclassifiedByUniqueId, fetchDistricts, storeAd } from 'apiCalls/apiEndpoints';
import { useFormik } from 'formik'
import FirstStep from './FirstStep';
import SecondStep from './SecondStep';
import { Upload } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import StandardContainer from '@/components/layout/StandardContainer'
import { useDistricts } from 'context/DistrictContext';
import { NextSeo } from 'next-seo';
import ImgCrop from 'antd-img-crop';
import * as Yup from 'yup';
import ImageWithFallback from '@/components/layout/ImageWithFallback';
import NextImage from '@/components/Images/NextImage';


const { Step } = Steps;

const steps = [
    {
        title: 'Basic Details',
        content: (
            <FirstStep />
        ),
    },
    {
        title: 'Ad Details',
        content: (
            <SecondStep />
        ),
    },
    {
        title: 'Verify and Submit',
        content: 'Last-content',
    },
];

const validate = (values: any) => {
    const errors: any = {};

    if (!values.title) {
        errors.title = 'Required';
    } else if (values.title.length > 15) {
        errors.title = 'Must be 15 characters or less';
    }

    // if (!values.lastName) {
    //     errors.lastName = 'Required';
    // } else if (values.lastName.length > 20) {
    //     errors.lastName = 'Must be 20 characters or less';
    // }

    // if (!values.email) {
    //     errors.email = 'Required';
    // } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    //     errors.email = 'Invalid email address';
    // }

    return errors;
};

// const getBase64 = (img: RcFile, callback: (url: string) => void) => {
//     const reader = new FileReader();
//     reader.addEventListener('load', () => callback(reader.result as string));
//     reader.readAsDataURL(img);
// };

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = error => reject(error);
    });

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};


const Post: NextPage = ({ districts }: any) => {

    const [categoryName, setCategoryName] = useState<any>('')
    const [subCategoryName, setSubCategoryName] = useState<any>('')


    //image upload stuff
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    //set districts
    const { setDistricts } = useDistricts()
    setDistricts(districts)

    const { data, isLoading: isRefetching } = useQuery(['districts'], fetchDistricts);
    const { data: classifiedsData, isLoading: isLoadingClassifieds } = useQuery(['classifieds'], classifiedsOnly);

    const [subclassifieds, setsubclassifieds] = useState<any>([])

    const { mutate, isLoading: gettingSubclassifields } = useMutation(classifiedById, {
        onSuccess: data => {
            console.log('sub classifieds', data.data.data)
            setsubclassifieds(data.data.data)
        }
    });

    const handleCategoryChange = (e: any) => {
        console.log(e)
        //fetch the classifieds
        mutate(e)
    }

    //post the ad mutation
    const { mutate: postAd, isLoading: ispostingad } = useMutation(storeAd, {
        onSuccess: data => {
            message.success('Your ad has been posted, its been reviewed for approval')
            router.push('/my-ads');
        },
        onError: (err: any) => {
            message.error(err?.message)
            router.push('/my-ads');
        }
    });



    const [sortOptions, setSortOptions] = useState('[]');
    const [parsedSortOptions, setParsedSortOptions] = useState<any>([]);
    const { mutate: getclassifiedProps } = useMutation(fetchclassifiedByUniqueId, {
        onSuccess: data => {
            setSortOptions(data.data.data[0].sort_options)
        }
    });

    useEffect(() => {
        console.log('sort options', JSON.parse(sortOptions ?? '[]'));
        setParsedSortOptions(JSON.parse(sortOptions ?? '[]'))
    }, [sortOptions])

    const handleSubCategoryChange = (e: any) => {
        console.log('sub category change', e)
        getclassifiedProps(e)
    }


    const router = useRouter();

    const [isLoading, setIsLoading] = useState(true);

    const { user, setUser } = useUser();


    const [fileListWithCrop, setFileListWithCrop] = useState<UploadFile[] | any>([])
    useEffect(() => {
        console.log('main images', fileListWithCrop)
    }, [fileListWithCrop])
    const onChangeImageWithCrop: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        setFileListWithCrop(newFileList);
    };

    const onPreviewImageWithCrop = async (file: UploadFile) => {
        let src = file.url as string;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj as RcFile);
                reader.onload = () => resolve(reader.result as string);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow?.document.write(image.outerHTML);
    };



    const [otherFileListWithCrop, setOtherFileListWithCrop] = useState<UploadFile[]>([])
    useEffect(() => {
        console.log('other images', otherFileListWithCrop)
    }, [otherFileListWithCrop])
    const onChangeOtherImageWithCrop: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        setOtherFileListWithCrop(newFileList);
    };
    const onPreviewOtherImageWithCrop = async (file: UploadFile) => {
        let src = file.url as string;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj as RcFile);
                reader.onload = () => resolve(reader.result as string);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow?.document.write(image.outerHTML);
    };



    //use state
    const [current, setCurrent] = useState(0);
    const next = () => {
        setCurrent(current + 1);
    };

    const prev = () => {
        setCurrent(current - 1);
    };

    useEffect(() => {
        console.log('classified data', classifiedsData?.data?.data)
    }, [classifiedsData?.data?.data])


    useEffect(() => {
        const token = getToken();
        if (!token) {
            router.push('/login');
        } else {
            setIsLoading(false);
        }
    }, [])

    const formik = useFormik({
        initialValues: {
            title: '',
            description: '',
            classified_id: '',
            sub_classified_id: '',
            price: ''
        },
        validationSchema: Yup.object().shape({
            title: Yup.string().required('Please add a title for your advert'),
            description: Yup.string().required('Please add a description to your advert'),
            classified_id: Yup.string().required('Please a select a classified category'),
            sub_classified_id: Yup.string().required('Please select a subclassified'),
            price: Yup.string().required('The price is required')
        }),
        onSubmit: values => {
            if (current != 2) {
                next()
            } else if (current === 2) {
                postAd({
                    description: values.description,
                    name: values.title,
                    classified_id: values.classified_id,
                    picture: fileListWithCrop[0]?.thumbUrl
                });
            }

        },
    });

    if (isLoading) {
        return (
            <div className='center mt-1'>
                <SyncLoader color='green' size={5} />
            </div>
        )
    }


    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            // getBase64(info.file.originFileObj as RcFile, url => {
            //     setLoading(false);
            //     setImageUrl(url);
            // });
        }
    };
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div className="ant-upload-text">Upload</div>
        </div>
    );

    const uploadButtonNew = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );



    return (
        <LayoutWithNav>
            <NextSeo
                title={`Post An Ad | Ashantiweb.com`}
                description={`Post An Ad`}
            />
            <StandardContainer>
                <div className='mx-auto lg:px-40'>
                    <Steps current={current}>
                        {steps.map(item => (
                            <Step key={item.title} title={item.title} />
                        ))}
                    </Steps>
                    <div className="steps-content">
                        <div className='my-10'>
                            {/* <Form layout='vertical'>
                                {steps[current].content}
                            </Form> */}
                            {/* {current === 0 && <FirstStep/>}
                            {current === 1 && <SecondStep/>} */}
                            <Form layout='vertical' onFinish={formik.handleSubmit}>
                                {current === 0 && (
                                    <Row>
                                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>
                                            <Form.Item name='title' label='Title' rules={[{ required: true, message: 'Please give your advert a title' }]}>
                                                <Input name='title' value={formik.values.title} onChange={formik.handleChange} onBlur={formik.handleBlur} />
                                            </Form.Item>

                                            {formik.touched.title && formik.errors.title ? (
                                                <div className='text-danger mb-4'>{formik.errors.title}</div>
                                            ) : null}
                                            {/* <span className='text-danger'>Title error<br /></span> */}
                                        </Col>
                                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>
                                            <Form.Item name='description' label='Description' rules={[{ required: true, message: 'Please give your advert a description' }]}>
                                                <Input.TextArea value={formik.values.description} onChange={formik.handleChange} onBlur={formik.handleBlur} />
                                            </Form.Item>
                                            {formik.touched.description && formik.errors.description ? (
                                                <div className='text-danger mb-4'>{formik.errors.description}</div>
                                            ) : null}
                                        </Col>
                                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>
                                            <Form.Item name='classified_id' label='Category' rules={[{ required: true, message: 'Please Select a category' }]}>
                                                {isLoadingClassifieds && 'please wait...'}
                                                <Select showSearch placeholder='Select a Category' onChange={(e: any) => {
                                                    handleCategoryChange(e)
                                                    formik.setFieldValue('classified_id', e)
                                                    console.log('category id', e)
                                                    setCategoryName(classifiedsData?.data?.data?.find((d: any) => d.id === e).name)
                                                }} disabled={isLoadingClassifieds} defaultValue={formik.values.classified_id}>
                                                    {classifiedsData?.data?.data?.map((d: any) =>
                                                        <Select.Option key={d.id} value={d.id}>{d.name}</Select.Option>
                                                    )}
                                                </Select>
                                            </Form.Item>
                                            {formik.touched.classified_id && formik.errors.classified_id ? (
                                                <div className='text-danger mb-4'>{formik.errors.classified_id}</div>
                                            ) : null}
                                        </Col>
                                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>
                                            <Form.Item name='sub_classified_id' label='Sub Category' rules={[{ required: true, message: 'Please Select a sub category' }]}>
                                                <Select showSearch placeholder='Select a Sub Category' onChange={(e: any) => {
                                                    handleSubCategoryChange(e)
                                                    formik.setFieldValue('sub_classified_id', e)
                                                    setSubCategoryName(subclassifieds?.find((d: any) => d.id === e).name)
                                                }} disabled={subclassifieds.length < 0} defaultValue={formik.values.sub_classified_id}>
                                                    {subclassifieds?.map((d: any) =>
                                                        <Select.Option key={d.id} value={d.id}>{d.name}</Select.Option>
                                                    )}
                                                </Select>
                                            </Form.Item>
                                            {formik.touched.sub_classified_id && formik.errors.sub_classified_id ? (
                                                <div className='text-danger mb-4'>{formik.errors.sub_classified_id}</div>
                                            ) : null}
                                        </Col>
                                        {/* {JSON.parse(
                                            subclassifieds.find((c: any) => c.id == formik.values.classified_id)?.sort_options ?? '[]'
                                        )?.find((o: any) => typeof (o) == 'object' && o.custom_sort
                                        )?.custom_sort?.find((op: any) => op.label?.includes('Price'))
                                            ? (
                                                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>
                                                    <Form.Item name='price' label='Price' rules={[{ required: true, message: 'Price' }]}>
                                                        <InputNumber style={{ width: '100%' }} formatter={value => `GH₵ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} parser={value => value?.replace(/GH₵\s?|(,*)/g, '')} />
                                                    </Form.Item>
                                                </Col>
                                            )
                                            : null} */}

                                        {parsedSortOptions.includes('price') ? (
                                            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>
                                                <Form.Item name='price' label='Price' rules={[{ required: true, message: 'The price is required' }]}>
                                                    <InputNumber name='price' onBlur={formik.handleBlur} onChange={(e: any) => formik.setFieldValue('price', e)} value={formik.values.price} style={{ width: '100%' }} formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}  />
                                                </Form.Item>
                                                {/* {formik.touched.price && formik.errors.price ? (
                                                    <div className='text-danger mb-4'>{formik.errors.price}</div>
                                                ) : null} */}
                                            </Col>
                                        ) : null}

                                        {/* <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>
                                            <Form.Item name='district_id' label='District'>
                                                <Select showSearch placeholder='Select a district' disabled={gettingSubclassifields}>
                                                    {data?.data?.map((d: any) =>
                                                        <Select.Option key={d.id} value={d.id}>{d.name}</Select.Option>
                                                    )}
                                                </Select>
                                            </Form.Item>
                                        </Col> */}
                                    </Row>
                                )}
                                {current === 1 && (
                                    <Row>
                                        {/* <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>
                                            <Form.Item name='picture' label='Picture'>
                                                <FileUpload
                                                    limit={1}
                                                    name='picture'
                                                    onChangeProp={v => {
                                                        setSecondStepValues({ ...secondStepValues, picture: v });
                                                    }}
                                                    defaultFileList={secondStepValues?.picture ? [
                                                        {
                                                            uid: secondStepValues?.picture,
                                                            name: secondStepValues?.picture?.split('/')[secondStepValues?.picture?.split('/').length - 1],
                                                            status: 'done',
                                                            url: secondStepValues?.picture?.includes('https') ? secondStepValues?.picture : `${process.env.APP_URL}/ashantiwebmedia/magic_temp/${secondStepValues?.picture}`,
                                                        }
                                                    ] : null} />
                                            </Form.Item>
                                            <p className='text-danger'>{status?.ad?.error?.picture?.join('<br />')}</p>
                                        </Col> */}
                                        <Col>
                                            <ImgCrop rotate>
                                                <Upload
                                                    listType="picture-card"
                                                    fileList={fileListWithCrop}
                                                    onChange={onChangeImageWithCrop}
                                                    onPreview={onPreviewImageWithCrop}
                                                >
                                                    {fileListWithCrop.length < 1 && '+ Upload'}
                                                </Upload>
                                            </ImgCrop>
                                        </Col>
                                        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 24 }} lg={{ span: 24 }}>

                                            <p>Other pictures</p>
                                            <div className='mt-2'>
                                                <p>show all other fields here</p>
                                                <ImgCrop rotate>
                                                    <Upload
                                                        listType="picture-card"
                                                        fileList={otherFileListWithCrop}
                                                        onChange={onChangeOtherImageWithCrop}
                                                        onPreview={onPreviewOtherImageWithCrop}
                                                    >
                                                        {otherFileListWithCrop.length < 5 && '+ Upload'}
                                                    </Upload>
                                                </ImgCrop>
                                                <div className=''>
                                                    {parsedSortOptions.length <= 0 ? '' :
                                                        parsedSortOptions.map((opt: any, i: any) => {
                                                            if (typeof opt === 'object') {
                                                                console.log('working', opt)
                                                                opt.custom_sort.map((it: any, i: number) => {
                                                                    console.log('label', it.label)
                                                                    return (<div className='' key={i}>
                                                                        <div>{it?.label}</div>
                                                                        <Select showSearch>
                                                                            {it?.options?.map((d: any, i: number) =>
                                                                                <Select.Option key={i} value={d.value}>{d.label}</Select.Option>
                                                                            )}
                                                                        </Select>
                                                                    </div>)
                                                                })
                                                                return (<p key={i}></p>)
                                                            }
                                                        })}
                                                </div>
                                            </div>
                                            {/* <Upload
                                                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                                listType="picture-card"
                                                fileList={fileList}
                                                onPreview={handlePreview}
                                                onChange={handleChange}
                                            >
                                                {fileList.length >= 8 ? null : uploadButton}
                                            </Upload>
                                            <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
                                                <Image alt="example" style={{ width: '100%' }} width='200' height='200' src={previewImage} />
                                            </Modal> */}
                                        </Col>
                                    </Row>

                                )}
                                {current === 2 && (
                                    <div className='text-center w-full flex flex-col items-center'>
                                        <h1 className='mb-2 mt-1 lg:mt-2'>Review your ad before posting</h1>
                                        <h2 className='mt-2'> <span className='text-gray-600'>Title</span>  <br /> <span className='text-lg '>{formik.values.title}</span> </h2>
                                        <h2 className='mt-4'> <span className='text-gray-600'>Category</span>  <br /> <span className='text-base text-gray-600'>{categoryName}  &gt; {subCategoryName}</span> </h2>
                                        <div className='relative w-40 h-40 rounded-sm text-center center mt-2'>
                                            {/* <Image className='rounded-full' src={fileListWithCrop[0]?.thumbUrl} alt='' layout='fill' /> */}
                                            <NextImage
                                                src={fileListWithCrop[0]?.thumbUrl}
                                                alt='thumbnail_image'
                                                layout="fill"
                                                className='rounded-full'
                                            />
                                        </div>
                                        <h1 className='mt-4 font-semibold text-gray-500'>All other pictures</h1>
                                        <div className='flex justify-center'>
                                            <div className='grid grid-cols-2 md:grid-cols-3 gap-4 mt-2'>
                                                {otherFileListWithCrop.map((item: any, index: number) => (
                                                    <div key={index} className='relative w-32 h-32 rounded-sm text-center'>
                                                        {/* <Image className='rounded-full' src={item?.thumbUrl} alt='' layout='fill' /> */}
                                                        <NextImage
                                                            src={fileListWithCrop[0]?.thumbUrl}
                                                            alt='thumbnail_image'
                                                            layout="fill"
                                                            className='rounded-full'
                                                        />
                                                    </div>
                                                ))}
                                            </div>
                                        </div>


                                    </div>
                                )}
                            </Form>
                        </div>
                    </div>
                    <div className="steps-action">
                        {current > 0 && (
                            <Button style={{ margin: '0 8px' }} onClick={() => prev()}>
                                Previous
                            </Button>
                        )}
                        {current < steps.length - 1 && (
                            <Button type="primary" htmlType='submit' onClick={() => {
                                // if (formik.errors // 👈 null and undefined check
                                //     && Object.keys(formik.errors).length === 0
                                //     && Object.getPrototypeOf(formik.errors) === Object.prototype) {
                                //     return;
                                // } else {
                                //     formik.handleSubmit()
                                //     next()
                                // }
                                formik.handleSubmit()

                                if (formik.errors) {
                                    return;
                                } else {
                                    // formik.handleSubmit()
                                    next()
                                }
                                // next()
                            }}>
                                Next
                            </Button>
                        )}
                        {current === steps.length - 1 && (
                            <Button type="primary" loading={ispostingad} htmlType='submit' onClick={() => {
                                ispostingad && message.loading('Ad is being posted')
                                formik.handleSubmit()
                            }}>
                                Submit
                            </Button>
                        )}

                    </div>
                </div>
            </StandardContainer>
        </LayoutWithNav>
    )
}

export default Post

export async function getServerSideProps({ req, res, params }: any) {
    const districts = await fetchDistricts()
    return {
        props: {
            districts: districts.data
        }
    }
}
