import { PageHeader } from "@ant-design/pro-layout";
import { useApolloClient, useMutation } from "@apollo/client/react";
import { Button, Card, Form, Popconfirm } from "antd";
import { phone } from "phone"; // Import phone utility for formatting
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { logImEXEvent } from "../../firebase/firebase.utils.js";
import { DELETE_OWNER, UPDATE_OWNER } from "../../graphql/owners.queries";
import { selectBodyshop } from "../../redux/user/user.selectors"; // Adjust path
import { phoneNumberOptOutService } from "../../utils/phoneOptOutService.js"; // Adjust path
import OwnerDetailFormComponent from "./owner-detail-form.component";

// Connect to Redux to access bodyshop
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

function OwnerDetailFormContainer({ owner, refetch, bodyshop }) {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [optedOutPhones, setOptedOutPhones] = useState(new Set());
  const [updateOwner] = useMutation(UPDATE_OWNER);
  const [deleteOwner] = useMutation(DELETE_OWNER);
  const notification = useNotification();
  const apolloClient = useApolloClient();

  // Fetch opt-out status on mount
  useEffect(() => {
    const fetchOptOutStatus = async () => {
      if (bodyshop?.id && bodyshop?.messagingservicesid && (owner?.ownr_ph1 || owner?.ownr_ph2)) {
        const phoneNumbers = [owner.ownr_ph1, owner.ownr_ph2].filter(Boolean);
        const optOutSet = await phoneNumberOptOutService(apolloClient, bodyshop.id, phoneNumbers);
        setOptedOutPhones(optOutSet);
      } else {
        setOptedOutPhones(new Set());
      }
    };

    fetchOptOutStatus();
  }, [apolloClient, bodyshop?.id, bodyshop?.messagingservicesid, owner?.ownr_ph1, owner?.ownr_ph2]);

  // Reset form fields when owner changes
  useEffect(() => {
    form.setFieldsValue({
      ownr_ph1: owner?.ownr_ph1,
      ownr_ph2: owner?.ownr_ph2,
      ...owner
    });
  }, [owner, form]);

  const handleDelete = async () => {
    setLoading(true);
    logImEXEvent("owner_delete", {});
    try {
      const result = await deleteOwner({
        variables: { id: owner.id }
      });
      if (result.errors) {
        notification.error({
          title: t("owners.errors.deleting", {
            error: JSON.stringify(result.errors)
          })
        });
      } else {
        notification.success({
          title: t("owners.successes.delete")
        });
        navigate(`/manage/owners`);
      }
    } catch (error) {
      notification.error({
        title: t("owners.errors.deleting", {
          error: error.message
        })
      });
    } finally {
      setLoading(false);
    }
  };

  const handleFinish = async (values) => {
    setLoading(true);
    logImEXEvent("owner_update", {});
    try {
      const result = await updateOwner({
        variables: { ownerId: owner.id, owner: values }
      });
      if (result.errors) {
        notification.error({
          title: t("owners.errors.saving", {
            error: JSON.stringify(result.errors)
          })
        });
      } else {
        notification.success({
          title: t("owners.successes.save")
        });
        if (refetch) await refetch();
        form.resetFields();
      }
    } catch (error) {
      notification.error({
        title: t("owners.errors.saving", {
          error: error.message
        })
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card>
      <PageHeader
        title={t("menus.header.owners")}
        extra={[
          <Popconfirm
            key="delete"
            trigger="click"
            onConfirm={handleDelete}
            disabled={owner.jobs.length !== 0}
            title={t("owners.labels.deleteconfirm")}
          >
            <Button type="primary" danger loading={loading} disabled={owner.jobs.length !== 0}>
              {t("general.actions.delete")}
            </Button>
          </Popconfirm>,
          <Button key="save" type="primary" loading={loading} onClick={() => form.submit()}>
            {t("general.actions.save")}
          </Button>
        ]}
      />
      <Form form={form} onFinish={handleFinish} autoComplete="off" layout="vertical" initialValues={owner}>
        <OwnerDetailFormComponent
          loading={loading}
          form={form}
          isPhone1OptedOut={
            bodyshop?.messagingservicesid &&
            owner?.ownr_ph1 &&
            optedOutPhones.has(phone(owner.ownr_ph1, "CA").phoneNumber?.replace(/^\+1/, ""))
          }
          isPhone2OptedOut={
            bodyshop?.messagingservicesid &&
            owner?.ownr_ph2 &&
            optedOutPhones.has(phone(owner.ownr_ph2, "CA").phoneNumber?.replace(/^\+1/, ""))
          }
        />
      </Form>
    </Card>
  );
}

export default connect(mapStateToProps)(OwnerDetailFormContainer);
