import { Alert, Button, Flex, Input, Modal, Space } from 'antd';
import React, { useState } from 'react'
import { TagOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { setCode } from '@/Redux/referralSlice';
import { RootState } from '@/Redux/store';
import Cookies from 'js-cookie';

const HaveReferral = () => {
    
    const dispatch = useDispatch();

    const _refCode = useSelector((state: RootState) => state.referral.code);

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [visible, setVisible] = useState(false);

    const handleClose = () => {
      setVisible(false);
    };

    const showModal = () => {
      setIsModalOpen(true);
    };
  
    const handleOk = () => {
      setIsModalOpen(false);
    };
  
    const handleCancel = () => {
      setIsModalOpen(false);
    };

    const handleReferralCodeChange = (e:any) => {
        const newValue = e.target.value
        // setReferralCode(newValue);
        dispatch(setCode(newValue))
        Cookies.set('referralCode', newValue, { expires: 1/24 });
      };

      const Apply = () =>{
        setVisible(true)
        handleCancel()
      }
    
  return (
    <>
    <div 
      onClick={showModal} 
      className='cursor-pointer underline m-2 text-sm opacity-90'
      
      >have a referral code ? <span className='text-primary_orange'>Tap here</span></div>
    <Modal 
    title="Referral Code" 
    open={isModalOpen} 
    onOk={handleOk} 
    onCancel={handleCancel}
    footer={null}
    width={300}
    >
        <Input placeholder="Enter referral code here" prefix={<TagOutlined />} 
        onChange={handleReferralCodeChange}
        value={_refCode}
        />
        <Flex gap="small" wrap="wrap" className='my-4'>
        <Button className='bg-primary_orange text-white hover:text-white' onClick={Apply}>Apply</Button>
        <Button className='bg-primary_orange text-white' onClick={handleCancel}>Cancel</Button>
        </Flex>
    </Modal>
    <Space direction="vertical" style={{ width: '100%' }}>
      {visible && (
        <Alert message={`Referral code : ${_refCode} applied.`} type="success" closable afterClose={handleClose} />
      )}
      {/* <p>click the close button to see the effect</p> */}
    </Space>
  </>
  )
}

export default HaveReferral