// AddSwitchModal.tsx
import React from 'react';
import { Modal, Form, Input } from 'antd';
import { userNameValidator } from '@/utills/validator';
import { updateChannelI } from '../interface';

interface AddSwitchModalProps {
    visible: boolean
    onOk: (name: string) => void
    onCancel: () => void
    channels:updateChannelI[]
}

const AddSwitchModal: React.FC<AddSwitchModalProps> = ({ visible, onOk, onCancel, channels }) => {
  const [form] = Form.useForm();
  const handleModalOk = () => {
    form.validateFields().then((values) => {
      if (channels.filter(f => f.channel.toLowerCase().trim() == values.channel_name.toLowerCase().trim()).length) {
        form.setFields([
          {
            name: 'channel_name',
            errors: ['This Channel Name is Already Exist.'],
          },
        ]);
        return false;
      }
      onOk(values.channel_name);
      form.setFieldValue('channel_name', '');
    });
  };

  const handleCancel = () => {
    onCancel();
    form.setFieldValue('channel_name', '');
  };

  return (
    <Modal
      title="Add New Source"
      visible={visible}
      onOk={() => {
        form.submit();
      }}
      onCancel={() => {
        form.resetFields();
        handleCancel();
      }}>
      <Form
        colon={false}
        form={form}
        onFinish={handleModalOk}
        labelAlign="left"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}>
        <Form.Item
          label="Name"
          name="channel_name"
          rules={[{ required: true, validator: userNameValidator('Channel') }]}>
          <Input placeholder="Enter the name for the new switch" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddSwitchModal;
