import TreeSelectedGroup from '@/components/shared/TreeSelectedGroup';
import { apiGetShipGroups } from '@/services/slave/sgw/ShipController';
import {
  ModalForm,
  ProForm,
  ProFormInstance,
  ProFormSlider,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useModel } from '@umijs/max';
import { AutoComplete, Col, Flex, Row, Select, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

interface SearchShipProps {
  initialValues?: Partial<SearchShipResponse>;
  things?: SgwModel.SgwThing[];
  isModalOpen: boolean;
  onClose: any;
  onSubmit: (values: SearchShipResponse) => void;
}

export interface SearchShipResponse {
  ship_name?: string;
  ship_length?: [number, number];
  reg_number?: string;
  ship_power?: [number, number];
  ship_type?: string | number;
  alarm_list?: string;
  ship_group_id?: string;
  group_id?: string | string[];
}

const ShipSearchForm = ({
  initialValues,
  things,
  isModalOpen,
  onClose,
  onSubmit,
}: SearchShipProps) => {
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUserProfile;
  const [group_id, setGroupId] = useState<string | string[] | null>(null);

  const [groupShips, setGroupShips] = useState<
    SgwModel.GroupShipResponse[] | []
  >([]);
  const [shipNames, setShipNames] = useState<string[]>([]);
  const [shipNameOptions, setShipNameOptions] = useState<
    { value: string; key: number }[]
  >([]);
  const [shipRegNumberOptions, setShipRegNumberOptions] = useState<
    { value: string; key: number }[]
  >([]);
  const formRef = useRef<ProFormInstance<SearchShipResponse>>();
  // console.log('InitialValue ', initialValues);

  useEffect(() => {
    if (initialValues === undefined && formRef.current) {
      formRef.current.resetFields();
    }
  }, [initialValues]);
  const [shipRegNumbers, setShipRegNumbers] = useState<string[]>([]);

  const { shipTypes, getShipTypes } = useModel('slave.sgw.useShipTypes');

  useEffect(() => {
    if (!shipTypes) {
      getShipTypes();
    }
  }, [shipTypes]);

  const getListShipNames = () => {
    if (things && Array.isArray(things)) {
      const names = things
        .map((item) => item?.metadata?.ship_name)
        .filter((name): name is string => Boolean(name)); // bỏ null/undefined/"" nếu có
      setShipNames(names);
    }
  };
  const handleGroupSelect = (group: string | string[] | null) => {
    // console.log("Selected group key:", value);
    setGroupId(group);
  };

  const handleSearchShipName = (value: string) => {
    if (!value) {
      setShipNameOptions([]); // không hiện gợi ý khi chưa nhập
      return;
    }
    const filtered = shipNames
      .filter((name) => name.toLowerCase().includes(value.toLowerCase()))
      .map((name, index) => ({ value: name, key: index }));
    setShipNameOptions(filtered);
  };

  const getListShipRegNumbers = () => {
    if (things && Array.isArray(things)) {
      const regNumbers = things
        .map((item) => item?.metadata?.ship_reg_number)
        .filter((reg): reg is string => Boolean(reg)); // bỏ null/undefined/"" nếu có
      setShipRegNumbers(regNumbers);
    }
  };
  const handleSearchShipRegNumber = (value: string) => {
    if (!value) {
      setShipRegNumberOptions([]); // không hiện gợi ý khi chưa nhập
      return;
    }
    const filtered = shipRegNumbers
      .filter((regNumber) =>
        regNumber.toLowerCase().includes(value.toLowerCase()),
      )
      .map((regNumber, index) => ({ value: regNumber, key: index }));
    setShipRegNumberOptions(filtered);
  };

  const getShipGroupByOwner = async () => {
    // console.log("Gọi hàm lấy ra đội tàu");

    try {
      const groups = await apiGetShipGroups();
      setGroupShips(groups);
      // console.log("Groups: ", groups);
    } catch (error) {
      console.error('Error when get ShipGroup: ', error);
    }
  };

  useEffect(() => {
    if (isModalOpen) {
      getListShipNames();
      getListShipRegNumbers();
      if (currentUser?.metadata?.user_type === 'enduser') {
        getShipGroupByOwner();
      }
    }
    // console.log("InitialData: ", initialData);
  }, [isModalOpen, things]);

  const alarmListLabel = [
    {
      label: 'Tiếp cận vùng hạn chế',
      value: '50:10',
    },
    {
      label: 'Đã ra (vào) vùng hạn chế)',
      value: '50:11',
    },
    {
      label: 'Đang đánh bắt trong vùng hạn chế',
      value: '50:12',
    },
  ];
  // console.log(
  //   'ShipSearchForm render - isModalOpen:',
  //   isModalOpen,
  //   'things length:',
  //   things?.length,
  // );

  return (
    <ModalForm
      title={
        <Flex align="center" justify="center">
          {intl.formatMessage({
            id: 'map.filter.name',
            defaultMessage: 'Filter',
          })}
        </Flex>
      }
      open={isModalOpen}
      onOpenChange={(open) => {
        // console.log('Modal onOpenChange:', open);
        if (!open) {
          onClose(false);
        }
      }}
      formRef={formRef}
      width={600}
      initialValues={initialValues}
      onFinish={async (values) => {
        // console.log("Values: ", values);
        // await onSubmit(values);
        const dataFinal: SearchShipResponse = {
          ship_name: values.ship_name,
          ship_length: values.ship_length,
          reg_number: values.reg_number,
          ship_power: values.ship_power,
          ship_type: values.ship_type,
          alarm_list: values.alarm_list,
          ship_group_id: values.ship_group_id,
          group_id: Array.isArray(group_id)
            ? group_id.join(',')
            : group_id || undefined,
        };
        // console.log("Values: ", dataFinal);
        onSubmit(dataFinal);
        onClose(false);
      }}
      modalProps={{
        cancelText: (
          <FormattedMessage
            id="map.filter.cancel_button"
            defaultMessage="Cancel"
          />
        ),
        okText: (
          <FormattedMessage id="map.filter.find_button" defaultMessage="Find" />
        ),
      }}
      layout="vertical"
      style={{ padding: '24px' }}
    >
      <Row gutter={[16, 16]}>
        <Col span={12}>
          <ProForm.Item
            name="ship_name"
            label={intl.formatMessage({
              id: 'map.filter.ship_name',
              defaultMessage: 'Ship Name',
            })}
            tooltip={intl.formatMessage({
              id: 'map.filter.ship_name_tooltip',
              defaultMessage: 'Find by Ship Name',
            })}
            fieldProps={{
              size: 'middle',
              style: { width: '100%' },
            }}
          >
            <AutoComplete
              placeholder="Hoàng Sa 001"
              style={{ width: '100%' }}
              size="middle"
              options={shipNameOptions}
              onSearch={handleSearchShipName}
            />
          </ProForm.Item>
        </Col>
        <Col span={12}>
          <ProForm.Item
            name="reg_number"
            tooltip={intl.formatMessage({
              id: 'map.filter.ship_reg_number_tooltip',
              defaultMessage: 'Find by Ship Registration Number',
            })}
            label={intl.formatMessage({
              id: 'map.filter.ship_reg_number',
              defaultMessage: 'Ship Registration Number',
            })}
            fieldProps={{
              size: 'middle',
              style: { width: '100%' },
            }}
          >
            <AutoComplete
              placeholder="VN-00001"
              style={{ width: '100%' }}
              size="middle"
              options={shipRegNumberOptions}
              onSearch={handleSearchShipRegNumber}
            />
          </ProForm.Item>
        </Col>
        <Col span={11} style={{ marginRight: 10 }}>
          <ProFormSlider
            range
            tooltip
            name="ship_length"
            label={intl.formatMessage({
              id: 'map.filter.ship_length',
              defaultMessage: 'Ship Length (m)',
            })}
            marks={{
              0: '0m',
              50: '50m',
              100: '100m',
            }}
            fieldProps={{
              style: { width: '80%' },
              tooltip: {
                formatter: (value) => `${value}m`,
              },
            }}
          />
        </Col>
        <Col span={11} style={{ marginLeft: 10 }}>
          <ProFormSlider
            range
            name="ship_power"
            label={intl.formatMessage({
              id: 'map.filter.ship_power',
              defaultMessage: 'Ship Power (kW)',
            })}
            max={100000}
            marks={{
              0: '0kW',
              50000: '50,000kW',
              100000: '100,000kW',
            }}
            fieldProps={{
              style: { width: '80%' },
              tooltip: {
                formatter: (value) => `${value}kW`,
              },
            }}
          />
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        <Col span={11}>
          <ProForm.Item
            name="ship_type"
            label={intl.formatMessage({
              id: 'map.filter.ship_type',
              defaultMessage: 'Ship Type',
            })}
          >
            <Select
              mode="multiple"
              allowClear
              style={{ width: '100%' }}
              placeholder={intl.formatMessage({
                id: 'map.filter.ship_type_placeholder',
                defaultMessage: 'Select Ship Type',
              })}
              options={(Array.isArray(shipTypes) ? shipTypes : []).map(
                (type) => ({
                  label: (
                    <Tooltip title={type.description}>{type.name}</Tooltip>
                  ),
                  value: type.id,
                }),
              )}
            />
          </ProForm.Item>
        </Col>
        <Col span={13}>
          <ProForm.Item
            name="alarm_list"
            label={intl.formatMessage({
              id: 'map.filter.ship_warning',
              defaultMessage: 'Warning',
            })}
          >
            <Select
              mode="multiple"
              allowClear
              style={{ width: '100%' }}
              placeholder={intl.formatMessage({
                id: 'map.filter.ship_warning_placeholder',
                defaultMessage: 'Select Warning',
              })}
              options={alarmListLabel}
            />
          </ProForm.Item>
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        <Col span={currentUser?.metadata?.user_type === 'enduser' ? 11 : 24}>
          <ProForm.Item
            name="group_id"
            label={intl.formatMessage({
              id: 'map.filter.area_type',
              defaultMessage: 'Area Type',
            })}
          >
            <TreeSelectedGroup
              groupIds={initialValues?.group_id}
              onSelected={handleGroupSelect}
              multiple
            />
          </ProForm.Item>
        </Col>
        {currentUser?.metadata?.user_type === 'enduser' && (
          <Col span={13}>
            <ProForm.Item
              name="ship_group_id"
              label={intl.formatMessage({
                id: 'map.filter.ship_groups',
                defaultMessage: 'Ship Groups',
              })}
            >
              <Select
                mode="multiple"
                allowClear
                style={{ width: '100%' }}
                placeholder={intl.formatMessage({
                  id: 'map.filter.ship_groups_placeholder',
                  defaultMessage: 'Select Ship Groups',
                })}
                options={groupShips?.map((group) => ({
                  label: (
                    <Tooltip title={group.description}> {group.name}</Tooltip>
                  ),
                  value: group.id,
                }))}
              />
            </ProForm.Item>
          </Col>
        )}
      </Row>
    </ModalForm>
  );
};

export default ShipSearchForm;
