import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { ModalForm } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, DatePicker, Flex, Form, Input, Select, Space } from 'antd';
import { FormListFieldData } from 'antd/lib';
import dayjs from 'dayjs';
import { useEffect } from 'react';
import { AreaCondition, ZoneFormField } from '../type';
const { RangePicker } = DatePicker;

// Transform form values to match AreaCondition type
const transformToAreaCondition = (values: any[]): AreaCondition[] => {
  return values.map((item) => {
    const { type } = item;

    switch (type) {
      case 'month_range': {
        // RangePicker for month returns [Dayjs, Dayjs]
        const [from, to] = item.from ?? [];
        return {
          type: 'month_range',
          from: from?.month() ?? 0, // 0-11
          to: to?.month() ?? 0,
        };
      }
      case 'date_range': {
        // RangePicker for date returns [Dayjs, Dayjs]
        const [from, to] = item.from ?? [];
        return {
          type: 'date_range',
          from: from?.format('YYYY-MM-DD') ?? '',
          to: to?.format('YYYY-MM-DD') ?? '',
        };
      }
      case 'length_limit': {
        return {
          type: 'length_limit',
          min: Number(item.min) ?? 0,
          max: Number(item.max) ?? 0,
        };
      }
      default:
        return item;
    }
  });
};

// Transform AreaCondition to form values
const transformToFormValues = (conditions?: AreaCondition[]): any[] => {
  if (!conditions || conditions.length === 0) return [{}];

  return conditions.map((condition) => {
    switch (condition.type) {
      case 'month_range': {
        return {
          type: 'month_range',
          from: [dayjs().month(condition.from), dayjs().month(condition.to)],
        };
      }
      case 'date_range': {
        return {
          type: 'date_range',
          from: [dayjs(condition.from), dayjs(condition.to)],
        };
      }
      case 'length_limit': {
        return condition;
      }
      default:
        return {};
    }
  });
};

const ConditionRow = ({
  field,
  remove,
}: {
  field: FormListFieldData;
  remove: (name: number) => void;
}) => {
  const selectedType = Form.useWatch([
    ZoneFormField.AreaConditions,
    field.name,
    'type',
  ]);
  const intl = useIntl();
  return (
    <Flex gap="middle" style={{ marginBottom: 16 }}>
      <Space align="baseline">
        <Form.Item
          name={[field.name, 'type']}
          label={intl.formatMessage({
            id: 'banzone.category.name',
            defaultMessage: 'Danh mục',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'banzone.category.not_empty',
                defaultMessage: 'Category cannot be empty!',
              }),
            },
          ]}
        >
          <Select
            placeholder={intl.formatMessage({
              id: 'banzone.category.add',
              defaultMessage: 'Add category',
            })}
          >
            <Select.Option value="month_range">
              <FormattedMessage
                id="banzone.condition.yearly_select"
                defaultMessage="Yearly"
              />
            </Select.Option>
            <Select.Option value="date_range">
              <FormattedMessage
                id="banzone.condition.specific_time_select"
                defaultMessage="Specific date"
              />
            </Select.Option>
            <Select.Option value="length_limit">
              <FormattedMessage
                id="banzone.condition.length_limit"
                defaultMessage="Length limit"
              />
            </Select.Option>
          </Select>
        </Form.Item>

        {selectedType !== undefined &&
          (selectedType === 'length_limit' ? (
            <Form.Item
              label={intl.formatMessage({
                id: 'banzone.condition.length_limit',
                defaultMessage: 'Length limit',
              })}
              required
            >
              <Space>
                <Form.Item
                  name={[field.name, 'min']}
                  noStyle
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({
                        id: 'common.not_empty',
                        defaultMessage: 'Cannot be empty!',
                      }),
                    },
                  ]}
                >
                  <Input
                    placeholder={intl.formatMessage({
                      id: 'banzone.condition.length_limit_min',
                      defaultMessage: 'Minimum',
                    })}
                    type="number"
                  />
                </Form.Item>
                <Form.Item
                  name={[field.name, 'max']}
                  noStyle
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({
                        id: 'common.not_empty',
                        defaultMessage: 'Cannot be empty!',
                      }),
                    },
                  ]}
                >
                  <Input
                    placeholder={intl.formatMessage({
                      id: 'banzone.condition.length_limit_max',
                      defaultMessage: 'Maximum',
                    })}
                    type="number"
                  />
                </Form.Item>
              </Space>
            </Form.Item>
          ) : (
            <Form.Item
              name={[field.name, 'from']}
              label={intl.formatMessage({
                id: 'banzone.condition.ban_time',
                defaultMessage: 'Time',
              })}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'common.not_empty',
                    defaultMessage: 'Cannot be empty!',
                  }),
                },
              ]}
            >
              <RangePicker
                picker={selectedType === 'month_range' ? 'month' : 'date'}
                format={
                  selectedType === 'month_range' ? 'MM/YYYY' : 'DD/MM/YYYY'
                }
              />
            </Form.Item>
          ))}

        <MinusCircleOutlined onClick={() => remove(field.name)} />
      </Space>
    </Flex>
  );
};

interface AddConditionFormProps {
  initialData?: AreaCondition[];
  isVisible: boolean;
  setVisible: (visible: boolean) => void;
  onFinish?: (values: AreaCondition[]) => void;
}

const AddConditionForm = ({
  initialData,
  isVisible,
  setVisible,
  onFinish,
}: AddConditionFormProps) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (isVisible) {
      form.resetFields();

      if (initialData && initialData.length > 0) {
        form.setFieldsValue({ conditions: transformToFormValues(initialData) });
      } else {
        form.setFieldsValue({ conditions: [{}] });
      }
    }
  }, [isVisible, initialData]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const transformedConditions = transformToAreaCondition(values.conditions);
      onFinish?.(transformedConditions);
      setVisible(false);
      form.resetFields();
    } catch (err) {
      console.error('Validation failed', err);
    }
  };

  return (
    <ModalForm
      form={form}
      open={isVisible}
      onOpenChange={(open) => {
        if (!open) form.resetFields();
        setVisible(open);
      }}
      title={
        <FormattedMessage
          id="banzone.category.add"
          defaultMessage="Add category"
        />
      }
      width="600px"
      submitter={{
        searchConfig: { submitText: 'Lưu' },
        render: (_, doms) => (
          <Flex justify="center" gap={16}>
            {doms}
          </Flex>
        ),
      }}
      onFinish={handleSubmit}
    >
      <Form.List name={ZoneFormField.AreaConditions}>
        {(fields, { add, remove }) => (
          <>
            {fields.map((field) => (
              <ConditionRow
                key={field.key}
                field={field}
                remove={remove}
                // isFirst={index === 0}
              />
            ))}
            <Form.Item>
              <Flex justify="center">
                <Button
                  type="dashed"
                  onClick={() => add()}
                  icon={<PlusOutlined />}
                  style={{ width: 300 }}
                >
                  <FormattedMessage
                    id="banzone.category.add"
                    defaultMessage="Add category"
                  />
                </Button>
              </Flex>
            </Form.Item>
          </>
        )}
      </Form.List>
    </ModalForm>
  );
};

export default AddConditionForm;
