import { useEffect, useState } from 'react';

import { Box, Button } from 'components/common';
import {
  BillingDetailsForm,
  BillingInformationFormValues,
} from './BillingDetailsForm';

export function isEmpty(data: Record<string, any>) {
  const result = Object.keys(data).every((key) => data[key] === '');
  return result;
}

const Line = ({
  label,
  value,
}: {
  label: string | number | null;
  value: string | number | null | undefined;
}) => {
  return (
    <div className="flex">
      <div className="flexNone w25">{label}</div>
      <div className="flexGrow bold">{value}</div>
    </div>
  );
};

export interface BillingInformationProps {
  data: BillingInformationFormValues;
  showForm?: boolean;
  disabled?: boolean;
}

export const BillingInformation = ({
  data,
  showForm,
  disabled,
}: BillingInformationProps) => {
  const [edit, setEdit] = useState<boolean>(Boolean(showForm) || false);
  const closeEditor = () => setEdit(false);

  useEffect(() => {
    setEdit(Boolean(showForm));
  }, [showForm]);

  const addData = isEmpty(data);

  return (
    <Box spacingY={5}>
      <div className="flex alignCenter justifyBetween">
        <div className="bold">Billing information</div>
        <div>
          {!edit ? (
            <Button
              onClick={() => setEdit(true)}
              color={addData ? 'blue' : 'gray'}
              disabled={disabled}
            >
              {addData ? 'Add' : 'Edit'}
            </Button>
          ) : (
            <Button onClick={closeEditor} color="gray" disabled={disabled}>
              Cancel
            </Button>
          )}
        </div>
      </div>

      {edit ? (
        <BillingDetailsForm initialState={data} onUpdate={closeEditor} />
      ) : (
        <Box spacingY={2} className="fz14">
          <Line label="Company:" value={data?.company} />
          <Line label="Email:" value={data?.email} />
          <Line label="Name:" value={data?.name} />
          <Line label="Phone:" value={data?.phone} />
          <Line label="VAT:" value={data?.vat} />

          <Line label="Address line 1:" value={data?.line1} />
          <Line label="Address line 2:" value={data?.line2} />
          <Line label="City:" value={data?.city} />
          <Line label="State:" value={data?.state} />
          <Line label="Country:" value={data?.country} />
          <Line label="Postal code:" value={data?.postalCode} />
        </Box>
      )}
    </Box>
  );
};
