import { Card, TextField } from "@shopify/polaris";
import { useGlobalContext } from "app/components/providers/global-context";
import Button from "app/components/ui/button";
import { UpdateAgentPayload } from "app/types";
import { useUpdateAgentDetails } from "app/utils/api";
import { useEffect, useMemo, useState } from "react";

export default function InstructionsTab() {
  const { agent } = useGlobalContext();
  const updateAgentMutation = useUpdateAgentDetails();
  const [instructions, setInstructions] = useState("");

  const handleUpdateAgent = async () => {
    const payload: UpdateAgentPayload = {
      chat_first_message: instructions,
    };
    try {
      await updateAgentMutation.mutateAsync({ _id: agent?._id!, payload });
    } catch (error) {}
  };

  const disbaleSaveButton = useMemo(() => {
    return instructions === agent?.chat_first_message;
  }, [instructions, agent?.chat_first_message]);

  useEffect(() => {
    if (agent?.chat_first_message) {
      setInstructions(agent?.chat_first_message);
    }
  }, [agent]);

  return (
    <Card>
      <TextField
        label="AI Instructions"
        value={instructions}
        onChange={setInstructions}
        multiline={6}
        placeholder={`Chat first message`}
        helpText="Write chat welcome message."
        autoComplete="off"
      />
      <div style={{ textAlign: "end", marginTop: "8px" }}>
        <Button
          disabled={disbaleSaveButton}
          // btnVariant="primary"
          btnSize="medium"
          onClick={handleUpdateAgent}
        >
          Save
        </Button>
      </div>
    </Card>
  );
}
