import { SettingOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client/react";
import { Button, Card, Col, Form, Popover, Row, Tabs } from "antd";
import { isFunction } from "lodash";
import PropTypes from "prop-types";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNotification } from "../../../contexts/Notifications/notificationContext.jsx";
import { UPDATE_KANBAN_SETTINGS } from "../../../graphql/user.queries.js";
import { defaultKanbanSettings, mergeWithDefaults } from "./defaultKanbanSettings.js";
import FilterSettings from "./FilterSettings.jsx";
import InformationSettings from "./InformationSettings.jsx";
import LayoutSettings from "./LayoutSettings.jsx";
import StatisticsSettings from "./StatisticsSettings.jsx";

function ProductionBoardKanbanSettings({ associationSettings, parentLoading, bodyshop, data, onSettingsChange }) {
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);
  const [statisticsOrder, setStatisticsOrder] = useState(defaultKanbanSettings.statisticsOrder);
  const [selectedMdInsCos, setSelectedMdInsCos] = useState(defaultKanbanSettings.selectedMdInsCos);
  const [selectedEstimators, setSelectedEstimators] = useState(defaultKanbanSettings.selectedEstimators);

  const [updateKbSettings] = useMutation(UPDATE_KANBAN_SETTINGS);
  const { t } = useTranslation();
  const notification = useNotification();

  useEffect(() => {
    if (associationSettings?.kanban_settings) {
      const finalSettings = mergeWithDefaults(associationSettings.kanban_settings);
      form.setFieldsValue(finalSettings);
      setStatisticsOrder(finalSettings.statisticsOrder);
      setSelectedMdInsCos(finalSettings.selectedMdInsCos);
      setSelectedEstimators(finalSettings.selectedEstimators);
    }
  }, [form, associationSettings]);

  const handleFinish = async (values) => {
    setLoading(true);
    parentLoading(true);

    const result = await updateKbSettings({
      variables: {
        id: associationSettings?.id,
        ks: {
          ...associationSettings.kanban_settings,
          ...values,
          statisticsOrder,
          selectedMdInsCos,
          selectedEstimators
        }
      }
    });

    if (result.errors) {
      notification.error({
        title: t("production.errors.settings", {
          error: JSON.stringify(result.errors)
        })
      });
    }

    setOpen(false);
    setLoading(false);
    parentLoading(false);

    if (onSettingsChange && isFunction(onSettingsChange)) {
      onSettingsChange(values);
    }

    setHasChanges(false);
  };

  const handleValuesChange = () => setHasChanges(true);

  const handleRestoreDefaults = () => {
    form.setFieldsValue({
      ...defaultKanbanSettings,
      statisticsOrder: defaultKanbanSettings.statisticsOrder
    });
    setStatisticsOrder(defaultKanbanSettings.statisticsOrder);
    setSelectedMdInsCos(defaultKanbanSettings.selectedMdInsCos);
    setSelectedEstimators(defaultKanbanSettings.selectedEstimators);
    setHasChanges(true);
  };

  const overlay = (
    <Card style={{ maxWidth: "80vw", width: "100%" }}>
      <Form form={form} onFinish={handleFinish} layout="vertical" onValuesChange={handleValuesChange}>
        <Tabs
          defaultActiveKey="1"
          items={[
            {
              key: "1",
              label: t("production.settings.layout"),
              children: <LayoutSettings t={t} />
            },
            {
              key: "2",
              label: t("production.settings.information"),
              children: <InformationSettings t={t} />
            },
            {
              key: "3",
              label: t("production.settings.statistics_title"),
              children: (
                <StatisticsSettings
                  t={t}
                  statisticsOrder={statisticsOrder}
                  setStatisticsOrder={setStatisticsOrder}
                  setHasChanges={setHasChanges}
                />
              )
            },
            {
              key: "4",
              label: t("production.settings.filters_title"),
              children: (
                <FilterSettings
                  selectedMdInsCos={selectedMdInsCos}
                  setSelectedMdInsCos={setSelectedMdInsCos}
                  selectedEstimators={selectedEstimators}
                  setSelectedEstimators={setSelectedEstimators}
                  setHasChanges={setHasChanges}
                  bodyshop={bodyshop}
                  data={data}
                />
              )
            }
          ]}
        />
        <Row justify="center" style={{ marginTop: 15 }} gutter={16}>
          <Col span={8}>
            <Button block onClick={() => setOpen(false)}>
              {t("general.actions.cancel")}
            </Button>
          </Col>
          <Col span={8}>
            <Button block onClick={handleRestoreDefaults}>
              {t("general.actions.defaults")}
            </Button>
          </Col>
          <Col span={8}>
            <Button block onClick={form.submit} loading={loading} type="primary" disabled={!hasChanges}>
              {t("general.actions.save")}
            </Button>
          </Col>
        </Row>
      </Form>
    </Card>
  );

  return (
    <Popover content={overlay} open={open} placement="topRight">
      <Button icon={<SettingOutlined />} loading={loading} onClick={() => setOpen(!open)}>
        {t("production.settings.board_settings")}
      </Button>
    </Popover>
  );
}

ProductionBoardKanbanSettings.propTypes = {
  associationSettings: PropTypes.object,
  parentLoading: PropTypes.func.isRequired,
  bodyshop: PropTypes.object.isRequired,
  onSettingsChange: PropTypes.func,
  data: PropTypes.array
};

export default ProductionBoardKanbanSettings;
