import React from "react";

import { Link } from "@mui/material";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";

import { countryCodeFormatter } from "../../../util/country_code_formatter";

export interface AddressLineProps {
  value?: string;
  icon?: JSX.Element;
  bold?: boolean;
}

export const AddressLine: React.FC<AddressLineProps> = ({ value, icon, bold = false }) =>
  value == null ? null : icon != null ? (
    <Stack alignItems="center" direction="row" gap={1}>
      {icon}
      <Typography noWrap fontWeight={bold ? 500 : 400} variant="body2">
        {value}
      </Typography>
    </Stack>
  ) : (
    <Typography noWrap fontWeight={bold ? 500 : 400} variant="body2">
      {value}
    </Typography>
  );

export interface AddressInfo {
  name?: string;
  givenName?: string;
  familyName?: string;
  companyName?: string;
  careOf?: string;
  streetAddress: string;
  streetAddress2?: string;
  postalCode: string;
  city: string;
  region?: string;
  countryCode: string;
  email?: string;
  phone?: string;
}

export interface AddressInfoProps {
  info: AddressInfo;
}

export const AddressInfo: React.FC<AddressInfoProps> = ({
  info: {
    name,
    givenName,
    familyName,
    companyName,
    careOf,
    streetAddress,
    streetAddress2,
    postalCode,
    city,
    region,
    countryCode,
    email,
    phone,
  },
}) => (
  <Stack direction="column" gap={0.5} sx={{ "& > a": { color: "text.primary" } }}>
    <AddressLine bold value={name} />
    <AddressLine bold value={companyName} />
    {Boolean(givenName || familyName) && (
      <AddressLine bold value={[givenName, familyName].join(" ")} />
    )}
    {careOf && <AddressLine value={`c/o ${careOf}`} />}
    <AddressLine value={streetAddress} />
    <AddressLine value={streetAddress2} />
    {Boolean(postalCode && city) && <AddressLine value={`${postalCode} ${city}`} />}
    <AddressLine value={region} />
    {countryCode != null && <AddressLine value={countryCodeFormatter.of(countryCode)} />}
    <Link href={`mailto:${email}`}>
      <AddressLine value={email} />
    </Link>
    <Link href={`tel:${phone}`}>
      <AddressLine value={phone} />
    </Link>
  </Stack>
);
