import { useIntl } from '@umijs/max';
import {
  Button,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
} from 'antd';
import { useEffect } from 'react';

// Camera types
const CAMERA_TYPES = [
  { label: 'HIKVISION', value: 'HIKVISION' },
  { label: 'DAHUA', value: 'DAHUA' },
  { label: 'GENERIC', value: 'GENERIC' },
];

interface CameraFormModalProps {
  open: boolean;
  onCancel: () => void;
  onSubmit: (camera: MasterModel.Camera) => void;
  isOnline?: boolean;
  editingCamera?: MasterModel.Camera | null;
}

const CameraFormModal: React.FC<CameraFormModalProps> = ({
  open,
  onCancel,
  onSubmit,
  isOnline = true,
  editingCamera,
}) => {
  const [form] = Form.useForm<MasterModel.Camera>();
  const intl = useIntl();
  const isEditMode = !!editingCamera;

  // Populate form when editing
  useEffect(() => {
    if (open && editingCamera) {
      form.setFieldsValue({
        ...editingCamera,
        cate_id: editingCamera.cate_id || 'HIKVISION',
        rtsp_port: editingCamera.rtsp_port || 554,
        http_port: editingCamera.http_port || 80,
      });
    } else if (open) {
      form.resetFields();
    }
  }, [open, editingCamera, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      // Values already in MasterModel.Camera format
      const camera: MasterModel.Camera = {
        ...editingCamera,
        ...values,
        // Ensure ID is set for new cameras
        id: editingCamera?.id || `cam_${Date.now()}`,
      };
      onSubmit(camera);
      form.resetFields();
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title={intl.formatMessage({
        id: isEditMode
          ? 'master.devices.camera.form.title.edit'
          : 'master.devices.camera.form.title.add',
        defaultMessage: isEditMode ? 'Chỉnh sửa camera' : 'Tạo mới camera',
      })}
      open={open}
      onCancel={handleCancel}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          {intl.formatMessage({
            id: 'master.devices.camera.form.cancel',
            defaultMessage: 'Hủy',
          })}
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          {intl.formatMessage({
            id: isEditMode
              ? 'master.devices.camera.form.update'
              : 'master.devices.camera.form.submit',
            defaultMessage: isEditMode ? 'Cập nhật' : 'Đồng ý',
          })}
        </Button>,
      ]}
      width={500}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          cate_id: 'HIKVISION',
          ip: '192.168.1.10',
          rtsp_port: 554,
          http_port: 80,
          stream: 0,
          channel: 0,
        }}
      >
        <Form.Item
          label={intl.formatMessage({
            id: 'master.devices.camera.form.name',
            defaultMessage: 'Tên',
          })}
          name="name"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'master.devices.camera.form.name.required',
                defaultMessage: 'Vui lòng nhập tên',
              }),
            },
          ]}
        >
          <Input
            placeholder={intl.formatMessage({
              id: 'master.devices.camera.form.name.placeholder',
              defaultMessage: 'nhập dữ liệu',
            })}
          />
        </Form.Item>

        <Form.Item
          label={intl.formatMessage({
            id: 'master.devices.camera.form.type',
            defaultMessage: 'Loại',
          })}
          name="cate_id"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'master.devices.camera.form.type.required',
                defaultMessage: 'Vui lòng chọn loại',
              }),
            },
          ]}
        >
          <Select options={CAMERA_TYPES} />
        </Form.Item>

        <Form.Item
          label={intl.formatMessage({
            id: 'master.devices.camera.form.username',
            defaultMessage: 'Tài khoản',
          })}
          name="username"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'master.devices.camera.form.username.required',
                defaultMessage: 'Vui lòng nhập tài khoản',
              }),
            },
          ]}
        >
          <Input
            placeholder={intl.formatMessage({
              id: 'master.devices.camera.form.username.placeholder',
              defaultMessage: 'nhập tài khoản',
            })}
            autoComplete="off"
          />
        </Form.Item>

        <Form.Item
          label={intl.formatMessage({
            id: 'master.devices.camera.form.password',
            defaultMessage: 'Mật khẩu',
          })}
          name="password"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'master.devices.camera.form.password.required',
                defaultMessage: 'Vui lòng nhập mật khẩu',
              }),
            },
          ]}
        >
          <Input.Password
            placeholder={intl.formatMessage({
              id: 'master.devices.camera.form.password.placeholder',
              defaultMessage: 'nhập mật khẩu',
            })}
            autoComplete="new-password"
          />
        </Form.Item>

        <Form.Item
          label={intl.formatMessage({
            id: 'master.devices.camera.form.ip',
            defaultMessage: 'Địa chỉ IP',
          })}
          name="ip"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'master.devices.camera.form.ip.required',
                defaultMessage: 'Vui lòng nhập địa chỉ IP',
              }),
            },
          ]}
        >
          <Input
            placeholder={intl.formatMessage({
              id: 'master.devices.camera.form.ip.placeholder',
              defaultMessage: '192.168.1.10',
            })}
          />
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={intl.formatMessage({
                id: 'master.devices.camera.form.rtspPort',
                defaultMessage: 'Cổng RTSP',
              })}
              name="rtsp_port"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'master.devices.camera.form.rtspPort.required',
                    defaultMessage: 'Vui lòng nhập cổng RTSP',
                  }),
                },
              ]}
            >
              <InputNumber style={{ width: '100%' }} min={0} max={65535} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={intl.formatMessage({
                id: 'master.devices.camera.form.httpPort',
                defaultMessage: 'Cổng HTTP',
              })}
              name="http_port"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'master.devices.camera.form.httpPort.required',
                    defaultMessage: 'Vui lòng nhập cổng HTTP',
                  }),
                },
              ]}
            >
              <InputNumber style={{ width: '100%' }} min={0} max={65535} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={intl.formatMessage({
                id: 'master.devices.camera.form.stream',
                defaultMessage: 'Luồng',
              })}
              name="stream"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'master.devices.camera.form.stream.required',
                    defaultMessage: 'Vui lòng nhập luồng',
                  }),
                },
              ]}
            >
              <InputNumber style={{ width: '100%' }} min={0} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={intl.formatMessage({
                id: 'master.devices.camera.form.channel',
                defaultMessage: 'Kênh',
              })}
              name="channel"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'master.devices.camera.form.channel.required',
                    defaultMessage: 'Vui lòng nhập kênh',
                  }),
                },
              ]}
            >
              <InputNumber style={{ width: '100%' }} min={0} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default CameraFormModal;
