import {
  ModalForm,
  ProFormItem,
  ProFormList,
} from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Flex, Input, theme } from 'antd';
import { useEffect, useMemo, useRef } from 'react';
import { PolygonGeometry, validateGeometry } from '../type';

interface PolygonModalProps {
  initialData?: PolygonGeometry[];
  index?: number;
  isVisible: boolean;
  setVisible: (visible: boolean) => void;
  handleSubmit: (values: PolygonGeometry[]) => Promise<void>;
}

const PolygonModal = ({
  isVisible,
  setVisible,
  handleSubmit,
  initialData,
  index,
}: PolygonModalProps) => {
  const formRef = useRef<any>();
  const { token } = theme.useToken();
  const intl = useIntl();
  // Counter to track item index during render
  let itemIndex = 0;
  // Convert initialData to form format
  const initialValues = useMemo(() => {
    if (!initialData || initialData.length === 0) {
      return { conditions: [] };
    }
    return {
      conditions: initialData.map((item) => ({
        geometry: JSON.stringify(item.geometry),
        id: item.id || undefined,
      })),
    };
  }, [initialData]);

  useEffect(() => {
    if (isVisible) {
      formRef.current?.setFieldsValue(initialValues);
    }
  }, [isVisible, initialValues]);

  // Handle form submit - convert back to AreaGeometry format
  const handleFinish = async (values: any) => {
    const conditions = values.conditions || [];
    const result: PolygonGeometry[] = conditions.map((item: any) => ({
      geometry: JSON.parse(item.geometry),
      id: item.id,
    }));
    await handleSubmit(result);
  };

  return (
    <>
      {/* Global style for highlighting TextArea border */}
      <style>{`
        .highlighted-item .ant-input {
          border-color: ${token.colorWarningActive} !important;
        }
      `}</style>
      <ModalForm
        formRef={formRef}
        open={isVisible}
        onOpenChange={(open) => {
          if (!open) formRef.current?.resetFields();
          setVisible(open);
        }}
        title={intl.formatMessage({
          id: 'banzone.polygon_modal.title',
          defaultMessage: 'Thêm toạ độ',
        })}
        width="40%"
        initialValues={initialValues}
        submitter={{
          searchConfig: {
            submitText: intl.formatMessage({
              id: 'common.save',
              defaultMessage: 'Lưu',
            }),
          },
          render: (_, doms) => (
            <Flex justify="center" gap={16}>
              {doms}
            </Flex>
          ),
        }}
        onFinish={handleFinish}
      >
        <ProFormList
          required
          name="conditions"
          creatorButtonProps={{
            position: 'bottom',
            creatorButtonText: intl.formatMessage({
              id: 'banzone.geometry.add_zone',
              defaultMessage: 'Thêm toạ độ',
            }),
          }}
          copyIconProps={false}
          deleteIconProps={{
            tooltipText: intl.formatMessage({
              id: 'common.delete',
              defaultMessage: 'Xoá',
            }),
          }}
          itemRender={({ listDom, action }) => {
            const currentIndex = itemIndex++;
            const isHighlighted = index !== undefined && currentIndex === index;
            return (
              <div
                className={isHighlighted ? 'highlighted-item' : ''}
                data-item-index={currentIndex}
              >
                {listDom}
                <Flex gap={8} justify="flex-end">
                  {action}
                </Flex>
              </div>
            );
          }}
        >
          {/* Hidden field for id - needed to preserve id when editing */}
          <ProFormItem name="id" hidden>
            <input type="hidden" />
          </ProFormItem>
          <ProFormItem
            name="geometry"
            required
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'banzone.geometry.coordinates.not_empty',
                  defaultMessage: 'Coordinates cannot be empty!',
                }),
              },
              {
                validator: (_rule: any, value: any) => {
                  return validateGeometry(value);
                },
              },
            ]}
            label={intl.formatMessage({
              id: 'banzone.geometry.coordinates',
              defaultMessage: 'Coordinates',
            })}
            tooltip={intl.formatMessage({
              id: 'banzone.geometry.coordinates.tooltip',
              defaultMessage:
                'Danh sách các toạ độ theo định dạng: [[longitude,latitude],[longitude,latitude],...]',
            })}
          >
            <Input.TextArea
              autoSize={{ minRows: 5, maxRows: 10 }}
              placeholder={intl.formatMessage({
                id: 'banzone.geometry.coordinates.placeholder',
                defaultMessage:
                  'Example: [[109.5, 12.3], [109.6, 12.4], [109.7, 12.5]]',
              })}
            />
          </ProFormItem>
        </ProFormList>
      </ModalForm>
    </>
  );
};

export default PolygonModal;
