import { useCallback, useEffect, useState } from 'react';
import { Button, Form } from 'antd';
import FormHeader from '../PageComponents/FormHeader';
import { Messages } from '../../Components/Notifications/Messages';
import TextAreaInput from '../../Components/Forms/TextArea';
import Buttons from '../../Components/Forms/Buttons';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage';
import { getSession } from '../../Services/Others';
import { useDispatch } from 'react-redux';
import { postEmpRelieve, getEmpRelieve, deleteEmpRelieve, putEmpRelieve } from '../../Features/EmpRelieve/EmpRelieve';
import { DatePicProd } from '../../Components/Forms/DatePickerProduct';
import moment from 'moment';
import dayjs from 'dayjs';
const subDirectory = import.meta.env.BASE_URL;
const items = [
    {
        name: 'Home',
        link: `${subDirectory}app-page/home`,
    },
    {
        name: 'Relieve-Request-Form',
        link: `${subDirectory}app-page/relieve-request`,
    },
];

const RelieveRequestForm = () => {
    const [form] = Form.useForm();
    const [message, setMessage] = useState({ type: '', data: '' });
    const [date, setDate] = useState("");
    const [reason, setReason] = useState("");
    const [edit, setEdit] = useState({ uniqueId: null, type: false });
    const dispatch = useDispatch();
    const AppId = getSession('AppId');
    const CompId = getSession('CompId');
    const BranchId = getSession('BranchId');
    const UserId = getSession('UserId');
    const onComplete = useCallback(() => {
        setMessage({ type: '', data: '' });
    }, [])

    useEffect(() => {
        try {
            dispatch(changeBreadCrumb({ items: items }));
            getEmpRelieveApi();
        } catch (err) {
            console.log(err, 'err');
        }
    }, []);

    const getEmpRelieveApi = async () => {
        const response = await dispatch(getEmpRelieve({ CompId, UserId, AppId, BranchId })).unwrap()
        if (response?.data?.statusCode === 1) {
            const relieveData = response?.data?.data;
            if (relieveData?.length > 0) {
                setEdit({ uniqueId: relieveData[0]?.UniqueId, type: true });
                const editDate = relieveData[0]?.RelieveDate ?
                    moment(relieveData[0]?.RelieveDate, ['YYYY-MM-DD']).format(
                        'YYYY-MM-DDTHH:mm:ss') : null;

                form.setFieldsValue({
                    RelieveDate: editDate,
                    RelieveReason: relieveData[0]?.RelieveReason || ''
                });
                setDate(editDate);
                setReason(relieveData[0]?.RelieveReason || '');
            }
        }
    }

    const onFinish = async (values) => {
        try {
            let response = {};
            const formattedDate = values.RelieveDate
            ? dayjs(values.RelieveDate).format('YYYY-MM-DD')
            : null;
            const postData = {
                AppId,
                CompId,
                BranchId,
                UserId,
                "RelieveDate": formattedDate,
                "RelieveReason": values.RelieveReason,
            }

            if (edit?.type) {
                response = await dispatch(putEmpRelieve({
                    ...postData,
                    "UniqueId": edit?.uniqueId,
                    "UpdatedBy": UserId
                }))?.unwrap();
            } else {
                response = await dispatch(postEmpRelieve({
                    ...postData,
                    "CreatedBy": UserId
                }))?.unwrap();
            }

            if (response?.data?.statusCode === 1) {
                setMessage({ type: 'success', data: response?.data?.response });
                getEmpRelieveApi();
            } else {
                setMessage({ type: 'error', data: response?.data?.response });
            }

        } catch (error) {
            setMessage({ type: 'error', data: 'Failed to submit relieve request. Please try again.' });
        }
    };

    const onFinishFailed = (errorInfo) => {
        setMessage({ type: 'error', data: 'Please fill in all required fields correctly.' });
    };

    const onDeleteEmpRelieve = async () => {
        try {
            const response = await dispatch(deleteEmpRelieve({ uniqueId : edit?.uniqueId, updatedBy : UserId, activeStatus : "D"})).unwrap();
            if (response?.data?.statusCode === 1) {
                setMessage({ type: 'success', data: response?.data?.response });
                form.resetFields();
                setDate("");
                setReason("");
                setEdit(false);
            } else {
                setMessage({ type: 'error', data: response?.data?.response });
            }
        } catch (error) {
            setMessage({ type: 'error', data: 'Failed to delete relieve request.' });
        }
    };

  const onDateChange = async (date, dateString) => {
    if (dateString) {
      const Date = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      form?.setFieldsValue({ RelieveDate: Date });
      setDate(Date);
    } else {
      form?.setFieldsValue({ RelieveDate: null });
      setDate(null);
    }
  };
    return (
        <div className="userPageTable">
            <div className="userPageContent">
                <Messages
                    messageType={message.type}
                    messageData={message.data}
                    onComplete={onComplete}
                />
                <div className="formAddNew">
                    <div style={{ display: 'flex' }}>
                        <FormHeader title={'Relieve Request'} />

                    </div>
                    <div className="reportTable">
                        <Form
                            form={form}
                            name="relieveRequest"
                            layout="vertical"
                            onFinish={onFinish}
                            onFinishFailed={onFinishFailed}
                        >
                            <Form.Item
                                label={
                                    <span style={{ fontWeight: '500', color: '#333' }}>
                                        Relieve Date
                                    </span>
                                }
                                name="RelieveDate"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please select relieve date!',
                                    },
                                ]}
                                style={{ marginBottom: '25px' }}
                            >
                                <DatePicProd
                                    valueData={date}
                                    canSelectPast={false} 
                                    onChange={onDateChange}
                                    />

                            </Form.Item>

                            <Form.Item
                                name="RelieveReason"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please provide reason for relieve!',
                                    },
                                    {
                                        min: 10,
                                        message: 'Reason must be at least 10 characters long!',
                                    },
                                ]}
                                style={{ marginBottom: '30px' }}
                            >
                                <TextAreaInput
                                    label={<label className='required'>Please provide your reason for Relieve...</label>}
                                    onChange={(e) => {
                                        form.setFieldsValue({ RelieveReason: e.target.value });
                                        setReason(e.target.value);
                                    }}
                                    defaultValue={reason}
                                    isOnChange={edit?.type}
                                    maxLength={250}
                                    showCount
                                    width={true}
                                />
                            </Form.Item>
                            <div style={{ display: 'flex', gap: '10px',width: '100%', justifyContent: 'flex-end' }}>
                                {edit?.type && (
                                    <Form.Item style={{ marginBottom: 0 }}>
                                        <Button
                                            type="default"
                                            onClick={onDeleteEmpRelieve}
                                            style={{
                                                width: '170px',
                                                height: '45px',
                                                backgroundColor: '#f5222d', 
                                                color: '#fff',
                                                fontFamily: 'var(--HEADING_FONT_FAMILY)',
                                                fontStyle: 'normal',
                                                fontWeight: 500,
                                                fontSize: '14px',
                                                borderRadius: '8px',
                                                display: 'flex',
                                                letterSpacing: '0.5px',
                                                justifyContent: 'space-between',
                                                alignItems: 'center',
                                                zIndex: 2,
                                                padding: '0 16px',
                                                border: 'none',
                                            }}
                                        >
                                            DELETE REQUEST
                                        </Button>
                                    </Form.Item>
                                )}
                                <Form.Item style={{ marginBottom: 0 }}>
                                    <Buttons
                                        buttonText="SUBMIT REQUEST"
                                        color="901D77"
                                    />
                                </Form.Item>
                            </div>
                        </Form>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default RelieveRequestForm;