// Copyright 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only

import React, { useState, useEffect, useMemo } from 'react';
import { action } from '@storybook/addon-actions';
import type { Meta } from '@storybook/react';
import type { PropsType } from './SafetyNumberViewer.dom.tsx';
import { SafetyNumberViewer } from './SafetyNumberViewer.dom.tsx';
import { getDefaultConversation } from '../test-helpers/getDefaultConversation.std.ts';

function generateQRData() {
  const data = new Uint8Array(128);
  for (let i = 0; i < data.length; i += 1) {
    data[i] = Math.floor(Math.random() * 256);
  }
  return data;
}

function generateNumberBlocks() {
  const result = new Array<string>();
  for (let i = 0; i < 12; i += 1) {
    let digits = '';
    for (let j = 0; j < 5; j += 1) {
      digits += Math.floor(Math.random() * 10);
    }
    result.push(digits);
  }
  return result;
}

const { i18n } = window.SignalContext;

const contactWithAllData = getDefaultConversation({
  title: 'Summer Smith',
  name: 'Summer Smith',
  phoneNumber: '(305) 123-4567',
  isVerified: true,
});

const contactWithJustProfile = getDefaultConversation({
  avatarUrl: undefined,
  title: '-*Smartest Dude*-',
  profileName: '-*Smartest Dude*-',
  name: undefined,
  phoneNumber: '(305) 123-4567',
});

const contactWithJustNumber = getDefaultConversation({
  avatarUrl: undefined,
  profileName: undefined,
  name: undefined,
  title: '(305) 123-4567',
  phoneNumber: '(305) 123-4567',
});

const contactWithNothing = getDefaultConversation({
  id: 'some-guid',
  avatarUrl: undefined,
  profileName: undefined,
  title: 'Unknown contact',
  name: undefined,
  phoneNumber: undefined,
});

const createProps = (overrideProps: Partial<PropsType> = {}): PropsType => ({
  contact: overrideProps.contact || contactWithAllData,
  i18n,
  safetyNumber:
    'safetyNumber' in overrideProps
      ? (overrideProps.safetyNumber ?? null)
      : {
          numberBlocks: generateNumberBlocks(),
          qrData: generateQRData(),
        },
  toggleVerified: action('toggle-verified'),
  verificationDisabled:
    overrideProps.verificationDisabled !== undefined
      ? overrideProps.verificationDisabled
      : false,
  keyTransparencyStatus: overrideProps.keyTransparencyStatus ?? 'idle',
  isKeyTransparencyEnabled: overrideProps.isKeyTransparencyEnabled ?? true,
  checkKeyTransparency: action('check-key-transparency'),
  onClose: overrideProps.onClose ?? action('onClose'),
});

export default {
  title: 'Components/SafetyNumberViewer',
} satisfies Meta<PropsType>;

export function SafetyNumber({
  onClose,
}: Partial<PropsType>): React.JSX.Element {
  return <SafetyNumberViewer {...createProps({ onClose })} />;
}

export function SafetyNumberNotVerified(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        contact: {
          ...contactWithAllData,
          isVerified: false,
        },
      })}
    />
  );
}

export function SafetyNumberKeyTransparencyRunning(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        contact: {
          ...contactWithAllData,
          isVerified: false,
        },
        keyTransparencyStatus: 'running',
      })}
    />
  );
}

export function SafetyNumberKeyTransparencyOk(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        contact: {
          ...contactWithAllData,
          isVerified: false,
        },
        keyTransparencyStatus: 'ok',
      })}
    />
  );
}

export function SafetyNumberKeyTransparencyFail(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        contact: {
          ...contactWithAllData,
          isVerified: false,
        },
        keyTransparencyStatus: 'fail',
      })}
    />
  );
}

export function SafetyNumberKeyTransparencyUnavailable(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        contact: {
          ...contactWithAllData,
          isVerified: false,
        },
        keyTransparencyStatus: 'unavailable',
      })}
    />
  );
}

export function SafetyNumberKeyTransparencyAnimation(): React.JSX.Element {
  const [status, setStatus] = useState<'idle' | 'running' | 'ok' | 'fail'>(
    'idle'
  );

  useEffect(() => {
    let counter = 0;

    const timer = setInterval(() => {
      setStatus(oldStatus => {
        switch (oldStatus) {
          case 'idle':
            return 'running';
          case 'running':
            return counter === 0 ? 'ok' : 'fail';
          default:
            return 'idle';
        }
      });
      counter = (counter + 1) % 2;
    }, 2000);

    return () => clearInterval(timer);
  }, []);

  const props = useMemo(() => {
    return createProps({
      contact: {
        ...contactWithAllData,
        isVerified: false,
      },
    });
  }, []);

  return <SafetyNumberViewer {...props} keyTransparencyStatus={status} />;
}

export function VerificationDisabled(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        verificationDisabled: true,
      })}
    />
  );
}

export function SafetyNumberDialogClose(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        onClose: action('close'),
      })}
    />
  );
}

export function JustProfileAndNumber(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        contact: contactWithJustProfile,
      })}
    />
  );
}

export function JustNumber(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        contact: contactWithJustNumber,
      })}
    />
  );
}

export function NoACICannotVerify(): React.JSX.Element {
  return (
    <SafetyNumberViewer
      {...createProps({
        contact: contactWithNothing,
        safetyNumber: undefined,
      })}
    />
  );
}
