import { Input, Text, Divider, Alert } from "@hubspot/ui-extensions";
import type { ContactInfo } from "../types";
import { useState } from "react";
import { isValidPhoneNumber } from "../helpers/formatPhoneNumber";
import { isValidEmail } from "../helpers/getBestEmail.helper";

interface Props {
  information: ContactInfo;
  showCreationError: string | null;
  isNewContact: boolean;
  setInformation: (info: ContactInfo) => void;
  handleUpdateChanges: () => void;
}

export const ManageContact = ({
  information,
  showCreationError,
  isNewContact,
  setInformation,
  handleUpdateChanges,
}: Props) => {
  const [showPhoneError, setShowPhoneError] = useState(false);
  const [showTelephoneError, setShowTelephoneError] = useState(false);
  const [showEmailError, setEmailError] = useState(false);
  return (
    <>
      {isNewContact && (
        <Alert title="Nuevo contacto" variant="tip">
          <Text>
            Contribuyente encontrado en ARCA, pero no encontrado en el CRM.
            Proceda para la creación del mismo.
          </Text>
        </Alert>
      )}
      <Input
        name="first_name"
        label="Nombre"
        value={information.name}
        readOnly
      />
      <Input
        name="last_name"
        label="Apellido"
        value={information.last_name}
        readOnly
      />
      <Input
        name="cuit_founded"
        label="CUIL/CUIT"
        value={information.cuit}
        readOnly
      />
      <Divider />
      <Text
        format={{
          textTransform: "uppercase",
          fontWeight: "demibold",
        }}
      >
        Datos de contacto
      </Text>
      <Input
        name="email"
        error={showCreationError === "Duplicate" || showEmailError}
        label="Email principal - Vinculado con CRM"
        validationMessage={
          showCreationError === "Duplicate"
            ? "El email ya existe"
            : showEmailError
              ? "El email ingresado no es válido"
              : ""
        }
        value={information.email}
        onChange={(value) => {
          setEmailError(!isValidEmail(value));
          setInformation({ ...information, email: value, email_type: "" });
          handleUpdateChanges();
        }}
        required
      />
      {showCreationError === "Duplicate" && (
        <Alert title="Encontramos otro contacto con este mismo email">
          Email ya se encuentra en la base. Por favor, solicita un correo
          electrónico alternativo
        </Alert>
      )}
      <Input
        name="mobile"
        label="Teléfono celular"
        required
        error={showPhoneError}
        validationMessage={
          showPhoneError ? "El número de teléfono ingresado no es válido" : ""
        }
        value={information.mobile}
        onChange={(value) => {
          setInformation({ ...information, mobile: value });
          handleUpdateChanges();
          setShowPhoneError(!isValidPhoneNumber(value));
        }}
      />
      <Divider />
      <Text
        format={{
          textTransform: "uppercase",
          fontWeight: "demibold",
        }}
      >
        Información de respaldo
      </Text>
      <Input
        name="landline"
        label="Teléfono fijo"
        required
        value={information.landline}
        error={showTelephoneError}
        validationMessage={
          showTelephoneError
            ? "El número de teléfono ingresado no es válido"
            : ""
        }
        onChange={(value) => {
          setInformation({ ...information, landline: value });
          handleUpdateChanges();
          setShowTelephoneError(!isValidPhoneNumber(value));
        }}
      />

      {showCreationError === "Creation" && (
        <Alert title="Error en la creación">
          Hubo un problema al crear el contacto. Intentelo nuevamente.
        </Alert>
      )}
      {showCreationError === "Update" && (
        <Alert title="Error en la actualización">
          Hubo un problema al actualizar el contacto. Intentelo nuevamente.
        </Alert>
      )}
    </>
  );
};
