import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import {
  EditFilled,
  DeleteFilled,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import FormHeader from '../PageComponents/FormHeader';
import { Messages } from '../../Components/Notifications/Messages';
import Buttons from '../../Components/Forms/Buttons';
import Search from '../../Components/Forms/Search';
import { Tables } from '../../Components/Tables/Table';
import { Form, Space } from 'antd';
import { DefaultModal } from '../../Components/Modal/DefaultModal';
import { InputField } from '../../Components/Forms/InputField';
import { getSession, validateSafeInput } from '../../Services/Others';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage';
import {
  deleteLanguages,
  getLanguages,
  postLanguages,
  putLanguages,
} from '../../Features/SpeechLanguages/SpeechLanguagesList.js';

const subDirectory = import.meta.env.BASE_URL;

const SpeechLanguagesList = () => {
  const formRef = useRef(null);
  const dispatch = useDispatch();
  const UserId = getSession('UserId');
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [page, setpage] = useState(1);
  const [sortedInfo, setSortedInfo] = useState({});
  const [searchedText, setSearchedText] = useState('');
  const [openModal, setOpenModal] = useState(false);
  const [editState, setEditState] = useState({});
  const [languagesData, setLanguagesData] = useState([]);
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },
  ];

  const columns = [
    {
      title: 'Sl.No',
      align: 'center',
      key: 'sno',
      width: '100px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Language',
      dataIndex: 'Language',
      key: 'Language',
      align: 'left',
      width: '250px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.Language)?.toLowerCase().includes(value?.toLowerCase()) ||
          String(record.Code)?.toLowerCase().includes(value?.toLowerCase())
        );
      },
      sorter: (a, b) => a?.Language?.localeCompare(b.Language),
      sortOrder: sortedInfo.columnKey === 'Language' ? sortedInfo.order : null,
      ellipsis: true,
    },
    {
      title: 'Code',
      dataIndex: 'Code',
      key: 'Code',
      align: 'left',
      width: '250px',
      render: (text) => <a style={{ color: 'black' }}>{text}</a>,
    },
    {
      title: 'Action',
      dataIndex: 'Action',
      key: 'Action',
      width: '200px',
      align: 'center',
      render: (_, record, index) =>
        languagesData?.length >= 1 ? (
          <Space size="middle">
            {record.ActiveStatus === 'A' ? (
              <a>
                <EditFilled
                  style={{ color: '#1292EE' }}
                  onClick={() => actionsFormatter(record, index)}
                />
              </a>
            ) : (
              ''
            )}
            <a>
              {record.ActiveStatus === 'A' ? (
                <DeleteFilled
                  style={{
                    color: '#FF4D4F',
                  }}
                  onClick={() => statusFormatter(record)}
                />
              ) : (
                <ReloadOutlined
                  style={{
                    color: '#52C41A',
                  }}
                  onClick={() => statusFormatter(record)}
                />
              )}
            </a>
          </Space>
        ) : null,
    },
  ];

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    fetchLanguages();
  }, []);

  useEffect(() => {
    if (Object.keys(editState)?.length > 0) {
      formRef?.current?.setFieldsValue({
        Language: editState?.Language,
        Code: editState?.Code,
      });
    }
  }, [editState]);

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const actionsFormatter = (record, index) => {
    setOpenModal(true);
    setEditState(record);
    formRef?.current?.setFieldsValue({
      Language: record?.Language,
      Code: record?.Code,
    });
  };

  const statusFormatter = async (record) => {
    let deleteData = {
      UniqueId: record.UniqueId,
      ActiveStatus: record.ActiveStatus == 'A' ? 'D' : 'A',
      UpdatedBy: UserId,
    };
    let response = await dispatch(deleteLanguages(deleteData)).unwrap();
    if (response?.data?.statusCode == 1) {
      setMessageType('success');
      setMessageData(
        record.ActiveStatus == 'A'
          ? 'In-Activated Successfully'
          : 'Activated Successfully'
      );

      fetchLanguages();
    }
  };

  const handlePageChange = (current) => {
    setpage(current);
  };

  const handleChange = (pagination, filters, sorter) => {
    setSortedInfo(sorter);
  };

  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };

  const openModalFun = () => {
    setEditState({});
    formRef?.current?.resetFields();
    setOpenModal(true);
  };

  const handleCancel = () => {
    setOpenModal(false);
  };

  const fetchLanguages = async () => {
    let response = await dispatch(getLanguages()).unwrap();
    if (response?.data?.statusCode == 1) {
      setLanguagesData(response?.data?.data);
    }
  };

  const handleSubmit = async () => {
    const subLangData = await formRef?.current?.validateFields();
    const addLangData = {
      Language: subLangData?.Language,
      Code: subLangData?.Code,
      CreatedBy: UserId,
    };

    let response = {};
    if (Object.keys(editState)?.length === 0) {
      response = await dispatch(postLanguages(addLangData)).unwrap();
    } else {
      const updateLangData = {
        UniqueId: editState?.UniqueId,
        Language: subLangData?.Language,
        Code: subLangData?.Code,
        UpdatedBy: UserId,
      };
      response = await dispatch(putLanguages(updateLangData)).unwrap();
    }
    if (response?.data?.statusCode == 1) {
      setMessageType('success');
      setMessageData(response?.data?.response);
      setOpenModal(false);
      setEditState({});
      formRef?.current?.resetFields();
      fetchLanguages();
    } else {
      setMessageType('error');
      setMessageData(response?.data?.response);
      // formRef?.current?.resetFields();
    }
  };

  return (
    <div className="userPageTable">
      <div className="userPageContent">
        <Messages
          messageType={messageType}
          messageData={messageData}
          onComplete={onComplete}
        />
        <div className="formAddNew">
          <div>
            <FormHeader title={'Languages'} />
          </div>
          <div className="searchAddDiv">
            <div className="formSearch">
              <Search
                placeholder="Search"
                onSearch={onSearch}
                onSearchChange={onSearchChange}
              />
            </div>

            <Buttons
              buttonText="Add New"
              color="901D77"
              handleSubmit={openModalFun}
            ></Buttons>
          </div>
        </div>
        <div className="reportTable">
          <Tables
            columns={columns}
            data={languagesData}
            pagination={handlePageChange}
            onChange={handleChange}
          />
        </div>
      </div>
      <DefaultModal
        title="Language"
        open={openModal}
        footer={true}
        children={
          <Form ref={formRef} className="formDivAnt">
            <div style={{ display: 'flex', gap: '1rem' }}>
              <div>
                <Form.Item
                  name="Language"
                  rules={[
                    {
                      required: true,
                      pattern: /^(?!\s*$).+/,
                      message: 'Please Enter Language',
                    },
                    {
                      validator: async (_, value) => {
                        await validateSafeInput(value); // To block HTML tags & SQL keywords
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <InputField
                    autoComplete="off"
                    label={<label class="required">Language</label>}
                    isOnChange={editState?.Language ? true : false}
                  />
                </Form.Item>
              </div>
              <div>
                <Form.Item
                  name="Code"
                  rules={[
                    {
                      required: true,
                      pattern: /^(?!\s*$).+/,
                      message: 'Please Enter Code',
                    },
                    {
                      validator: async (_, value) => {
                        await validateSafeInput(value); // To block HTML tags & SQL keywords
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <InputField
                    autoComplete="off"
                    label={<label class="required">Code</label>}
                    isOnChange={editState?.Code ? true : false}
                  />
                </Form.Item>
              </div>
            </div>
          </Form>
        }
        handleCancel={handleCancel}
        handleSubmit={handleSubmit}
      ></DefaultModal>
    </div>
  );
};

export default SpeechLanguagesList;
