import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { usePathname, useRouter } from 'next/navigation';
import {
  Input,
  Button,
  Card,
  Form,
  Switch,
  Row,
  Col,
  Modal,
  Select,
  notification,
  Spin,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { fetchFacebookFormList } from '../slice';
import type { AppDispatch, RootState } from '@/store/store';
import type { ChannelFormDataI, ChannelI, ProjectFormValuesI, updateChannelI } from '../interface';
import { getProjectChannel, updateProjectMarketingChannel } from '../service';
import { useSession } from 'next-auth/react';
import { createSlug, hasPermission } from '@/utills/helper';
import { PERMISSIONS } from '@/utills/constant';
import AddSwitchModal from './AddSwitchModal';
import { DataType } from '@/app/designations/interface';

interface MarketingPropsI {
    projectID: number | string | any
    hideCancelButton?: boolean
    isCard?: boolean
    onSaveSuccess?: () => void
}

const MarketingChannel: React.FC<MarketingPropsI> = ({
  projectID,
  hideCancelButton = false,
  isCard = true,
  onSaveSuccess,
}) => {
  const router = useRouter();
  const pathName = usePathname();
  const [form] = Form.useForm();
  const dispatch: AppDispatch = useDispatch();
  const [editProjectName, setEditProjectName] = useState('');
  const [fetchLoading, setFetchLoading] = useState<boolean>(false);
  const [submitionLoading, setSubmitionLoading] = useState<boolean>(false);
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false);
  const facebookFormList = useSelector((state: RootState) => state?.launches?.faceBookList);
  const { data: session } = useSession();
  const user = session?.user;

  // Check user permissions
  const isEditable = hasPermission(user, PERMISSIONS.PROJECT_CREATE.name);

  // Initial marketing channels
  const initialChannels = [
    {
      channel: 'Google',
      channel_label: 'Google',
      channel_id: 'google',
      enabled: pathName === '/launches/add-projects',
      inputType: 'text',
    },
    {
      channel: 'Facebook',
      channel_label: 'Facebook',
      channel_id: 'facebook',
      enabled: pathName === '/launches/add-projects',
      inputType: 'select',
    },
    {
      channel: 'Whatsapp',
      channel_label: 'Whatsapp',
      channel_id: 'whatsapp',
      enabled: pathName === '/launches/add-projects',
      inputType: 'text',
    },
    {
      channel: 'Housiey',
      channel_label: 'Housiey',
      channel_id: 'housiey',
      enabled: pathName === '/launches/add-projects',
      inputType: 'text',
    },
    {
      channel: 'Youtube',
      channel_label: 'Youtube',
      channel_id: 'youtube',
      enabled: pathName === '/launches/add-projects',
      inputType: 'text',
    },
  ];
  const [channels, setChannels] = useState<updateChannelI[]>(initialChannels);

  // Set form fields based on channel data
  const setFormFields = (channelsData: ChannelI[]) => {
    const fieldsValue: DataType = {};
    channelsData.forEach((channel: ChannelI) => {
      fieldsValue[channel.channel_id] = channel.enabled;
      const inputKey =
                channel.inputType === 'select'
                  ? `select-${channel.channel}`
                  : `input-${channel.channel}`;
      if (channel.channel_id) {
        fieldsValue[inputKey] = channel.channel_id;
      }
    });
    form.setFieldsValue(fieldsValue);
  };

  useEffect(() => {
    if (projectID) {
      fetchChannels();
      getFaceBookFormList();
    }
  }, [projectID]);

  // Fetch marketing channels
  const fetchChannels = async() => {
    if (projectID !== undefined && projectID !== null) {
      try {
        setFetchLoading(true);
        setChannels(initialChannels);
        form.resetFields();
        await getProjectChannel(projectID)
          .then((response) => {
            const channelData = response?.data;
            const project = response?.project.name;
            const slug = createSlug(project);
            setEditProjectName(slug);
            if (channelData && channelData.length > 0) {
              const updatedChannels = channelData?.map((c: ChannelI) => ({
                channel: c.channel,
                enabled: c.status === 'active',
                id: c.id,
                channel_id: c.channel_id,
                channel_name: c.channel_name,
                inputType:
                                    c.channel.toLowerCase() === 'facebook' ? 'select' : 'text',
              }));
              setChannels(updatedChannels);
              setFormFields(updatedChannels);
            } else {
              const fieldsValue: DataType = {};

              initialChannels.forEach((channel) => {
                fieldsValue[channel.channel_id] = channel.enabled;
                const inputKey =
                                    channel.inputType === 'select'
                                      ? `select-${channel.channel}`
                                      : `input-${channel.channel}`;
                if (channel.channel_id != 'facebook') {
                  fieldsValue[inputKey] = slug;
                }
              });
              setChannels(initialChannels);

              form.setFieldsValue(fieldsValue);
            }
          })
          .catch((error) => {
            console.error('error', error);
          });
      } catch (error) {
        console.error('error', error);
      }
      setFetchLoading(false);
    }
  };

  // Fetch Facebook form list
  const getFaceBookFormList = (): void => {
    dispatch(fetchFacebookFormList({ projectID }))
      .then((res) => {
        console.log('res: ', res);
      })
      .catch((error) => {
        console.error('error: ', error);
      });
  };

  useEffect(() => {
    fetchChannels();
    getFaceBookFormList();
  }, []);

  const handleAddSwitch = (): void => {
    setAddModalVisible(true);
  };

  const handleModalOk = (name: string): void => {
    const newChannel = {
      channel: name,
      enabled: true,
      inputType: 'text',
      channel_id: name.toLowerCase(),
    };
    const updatedChannels = [...channels, newChannel];
    setChannels(updatedChannels);
    const key = `input-${newChannel.channel}`;
    form.setFieldsValue({ [key]: editProjectName });
    setAddModalVisible(false);
  };

  const handleFormSubmit = (formValues: ChannelFormDataI): void => {
    setSubmitionLoading(true);
    const activeChannelsPayload = channels?.map((channel) => {
      const inputKey =
                channel.inputType === 'select'
                  ? `select-${channel.channel}`
                  : `input-${channel.channel}`;
      const changedValue = formValues[inputKey];
      return {
        id: channel.id,
        channel: channel.channel?.toLowerCase(),
        channel_id: changedValue ? changedValue.toString() : '',
        status: channel.enabled ? 'active' : 'inactive',
      };
    });
    const payload: { channels: any[]; isProjectCreate?: number } = {
      channels: activeChannelsPayload,
    };

    if (pathName === '/launches/add-projects') {
      payload.isProjectCreate = 1;
    }
    try {
      updateProjectMarketingChannel(projectID, payload)
        .then((response) => {
          Modal.success({
            title: 'Success',
            content: response?.message,
            okText: 'Okay',
            onOk() {
              if (onSaveSuccess) {
                onSaveSuccess();
              } else {
                router.push('/launches?Projects=1');
              }
            },
          });
          setSubmitionLoading(false);
        })
        .catch((error) => {
          const { message } = error?.response?.data || {};
          notification.error({
            message: 'Error',
            description: message,
          });
          setSubmitionLoading(false);
        });
    } catch (error) {
      console.error('error: ', error);
    }
  };

  const handleChannelUpdate = (updatedChannel: ChannelI) => {
    setChannels((prevChannels: any) => {
      return prevChannels?.map((ch: ChannelI) =>
        ch.channel === updatedChannel.channel && ch.id === updatedChannel.id
          ? updatedChannel
          : ch
      );
    });
    form.setFieldsValue({
      [updatedChannel.channel_id]: true,
    });
    form.validateFields();
  };

  const formElement = () => (
    <Form onFinish={handleFormSubmit} form={form}>
      {channels?.map((channel, index) => {
        return (
          <Row key={index}>
            <Col xs={24} sm={8} lg={6}>
              <Form.Item
                label={channel?.channel}
                name={channel?.channel_id}
                className="capitalize switch-item">
                <Switch
                  disabled={!isEditable}
                  checked={channel.enabled}
                  onChange={(checked) => {
                    const updatedChannel: any = {
                      ...channel,
                      enabled: checked,
                    };
                    handleChannelUpdate(updatedChannel);
                  }}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={6} lg={5}>
              <label className="marketing-channels-label">
                {channel.channel}{' '}
                {channel.enabled ? <span className="asterisk">*</span> : null}
              </label>
            </Col>
            <Col xs={24} sm={10} lg={10}>
              {channel?.inputType === 'select' ? (
                <Form.Item
                  label=""
                  name={`select-${channel.channel}`}
                  rules={[
                    {
                      required: channel.enabled,
                      message: 'Please Select an Option',
                    },
                  ]}>
                  <Select
                    placeholder="Select an option"
                    disabled={!channel.enabled}
                    allowClear={channel.enabled}>
                    {facebookFormList?.map((form: ProjectFormValuesI) => (
                      <Select.Option value={form.form_id} key={form.form_id}>
                        {form.name}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              ) : (
                <Form.Item
                  label=""
                  name={`input-${channel.channel}`}
                  rules={[
                    {
                      required: channel.enabled,
                      message: 'This Field is Required',
                    },
                    {
                      max: 150,
                      message: 'Must be up to 150 Characters',
                    },
                  ]}>
                  <Input
                    placeholder="Enter information"
                    disabled={!channel.enabled}
                  />
                </Form.Item>
              )}
            </Col>
          </Row>
        );
      })}
      {isEditable && (
        <Button
          type="dashed"
          onClick={handleAddSwitch}
          icon={<PlusOutlined />}
          size="large"
          className="mt-5">
                    Add New Source
        </Button>
      )}
      {isEditable && (
        <div
          className="mt-5"
          style={{
            display: 'flex',
            justifyContent: 'flex-end',
          }}>
          {hideCancelButton ? null : (
            <Button
              type="default"
              onClick={() => {
                router.push('/launches?Projects=1');
              }}>
                            Cancel
            </Button>
          )}
          {pathName === '/launches/add-projects' ? (
            <Button
              type="primary"
              className="ml-3"
              htmlType="submit"
              loading={submitionLoading}>
                            Save
            </Button>
          ) : (
            <Button
              type="primary"
              className="ml-3"
              htmlType="submit"
              loading={submitionLoading}>
                            Update
            </Button>
          )}
        </div>
      )}
    </Form>
  );

  return (
    <>
      <Spin size="large" spinning={fetchLoading}>
        {isCard ? (
          <Card title="Marketing Channels" className="marketing-channels-section">
            {formElement()}
          </Card>
        ) : (
          <div className="marketing-channels-section">{formElement()}</div>
        )}
      </Spin>
      <AddSwitchModal
        visible={addModalVisible}
        channels={channels}
        onOk={handleModalOk}
        onCancel={() => {
          setAddModalVisible(false);
        }}
      />
    </>
  );
};

export default MarketingChannel;
