import { Meta, StoryObj } from '@storybook/react-webpack5';
import { Breakpoint } from '@transferwise/neptune-tokens';
import { useState } from 'react';
import { createSandboxStory, globalScope } from '../../.storybook/components/sandbox/SandboxEditor';
import AvatarView from '../avatarView';
import Body from '../body';
import Button from '../button';
import { ProfileType, Typography } from '../common';
import Logo from '../logo';
import OverlayHeader from '../overlayHeader';
import { lorem10 } from '../test-utils';
import Display from '../display';
import Sticky from '../sticky';

import FlowNavigation, { FlowNavigationProps } from './FlowNavigation';
import Container from '../container';

interface CustomControls {
  showCloseButton: boolean;
  showMobileBackButton: boolean;
  avatarURL?: string;
  profileType?: ProfileType;
}
export type StoryArgs = FlowNavigationProps & CustomControls;

type Story = StoryObj<StoryArgs>;

/**
 * FlowNavigation component for multi-step flows with progress tracking.
 *
 * **Border Behavior:**
 * - Non-composable (default): Border respects `done` prop when `showBottomBorder=true`.
 * - Composable: Border controlled only by `showBottomBorder`, ignoring the `done` property.
 **/
const meta: Meta<StoryArgs> = {
  component: FlowNavigation,
  title: 'Navigation/FlowNavigation',
  argTypes: {
    showCloseButton: { control: 'boolean', defaultValue: true },
    showMobileBackButton: { control: 'boolean', defaultValue: true },
    done: { control: 'boolean', defaultValue: false },
    showBottomBorder: { control: 'boolean', defaultValue: true },
    avatarURL: { control: 'text', defaultValue: '../tapestry-01.png' },
    profileType: {
      control: 'radio',
      options: [ProfileType.PERSONAL, ProfileType.BUSINESS],
      defaultValue: ProfileType.PERSONAL,
    },
  },
  parameters: {
    docs: {
      source: { type: 'code' },
    },
  },
};
export default meta;

const viewports = [
  Breakpoint.EXTRA_SMALL - 10,
  Breakpoint.EXTRA_SMALL + 10,
  Breakpoint.SMALL + 10,
  Breakpoint.MEDIUM + 10,
  Breakpoint.LARGE + 10,
];

export const Sandbox = createSandboxStory({
  code: `const App = () => {
  const [activeStep, setActiveStep] = React.useState(0);

  return (
    <FlowNavigation
      avatar={<AvatarView profileType={ProfileType.PERSONAL} />}
      logo={<Logo />}
      activeStep={activeStep}
      onClose={() => console.log('close')}
      onGoBack={() => setActiveStep((prev) => (prev > 0 ? prev - 1 : 0))}
      steps={[
        { label: 'Amount', hoverLabel: '100 GBP', onClick: () => setActiveStep(0) },
        { label: 'You', hoverLabel: 'Elena Durante', onClick: () => setActiveStep(1) },
        { label: 'Recipient', hoverLabel: 'Daniele Tomboro', onClick: () => setActiveStep(2) },
        { label: 'Review', onClick: () => setActiveStep(3) },
        { label: 'Pay', onClick: () => setActiveStep(4) },
      ]}
    />
  );
};`,
  scope: globalScope,
});

export const Variants: Story = {
  args: {
    profileType: ProfileType.PERSONAL,
    showCloseButton: true,
    showMobileBackButton: true,
    done: false,
    avatarURL: '../tapestry-01.png',
  },
  parameters: {
    chromatic: {
      viewports,
    },
  },
  render: (args) => {
    const [activeStep, setActiveStep] = useState(2);
    const [closed, setClosed] = useState(false);
    if (closed) return <></>;
    return (
      <>
        <FlowNavigation
          avatar={args.profileType ? <AvatarView profileType={args.profileType} /> : null}
          logo={<Logo />}
          activeStep={activeStep}
          done={args.done}
          steps={[
            {
              label: 'Amount',
              hoverLabel: <strong>100 GBP</strong>,
              onClick: () => setActiveStep(0),
            },
            {
              label: 'You',
              hoverLabel: <>Elena Durante - elenadurante@test.com</>,
              onClick: () => setActiveStep(1),
            },
            { label: 'Recipient', hoverLabel: 'Daniele Tomboro', onClick: () => setActiveStep(2) },
            { label: 'Review', hoverLabel: 'Antonio Dozortevo', onClick: () => setActiveStep(3) },
            {
              label: 'Pay',
              hoverLabel: 'Enrico Gusso II',
              onClick: () => setActiveStep(4),
            },
          ]}
          onClose={args.showCloseButton ? () => setClosed(true) : undefined}
          onGoBack={
            args.showMobileBackButton
              ? () => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)
              : undefined
          }
        />

        <FlowNavigation
          done={args.done}
          activeStep={activeStep}
          steps={[
            {
              label: 'Amount',
              hoverLabel: (
                <>
                  <div>
                    <strong>100 GBP</strong>
                  </div>
                  0.2351 ETH
                </>
              ),
              onClick: () => setActiveStep(0),
            },
            {
              label: 'You',
              hoverLabel: (
                <>
                  <div>
                    <strong>Elena Durante</strong>
                  </div>
                  elenadurante@test.com
                </>
              ),
              onClick: () => setActiveStep(1),
            },
            { label: 'Recipient', hoverLabel: 'Daniele Tomboro', onClick: () => setActiveStep(2) },
            { label: 'Review', hoverLabel: 'Antonio Dozortevo', onClick: () => setActiveStep(3) },
            {
              label: 'Pay',
              hoverLabel: 'Enrico Gusso II',
              onClick: () => setActiveStep(4),
            },
          ]}
          onClose={args.showCloseButton ? () => setClosed(true) : undefined}
          onGoBack={
            args.showMobileBackButton
              ? () => setActiveStep(activeStep - 1 > 0 ? activeStep - 1 : 0)
              : undefined
          }
        />

        <FlowNavigation
          done={args.done}
          avatar={<AvatarView imgSrc={args.avatarURL} profileType={args.profileType} />}
          activeStep={activeStep}
          steps={[
            {
              label: 'Amount',
              hoverLabel: (
                <>
                  <div>
                    <strong>100 GBP</strong>
                  </div>
                  0.2351 ETH
                </>
              ),
              onClick: () => setActiveStep(0),
            },
            {
              label: 'You',
              hoverLabel: (
                <>
                  <div>
                    <strong>Elena Durante</strong>
                  </div>
                  elenadurante@test.com
                </>
              ),
              onClick: () => setActiveStep(1),
            },
            { label: 'Recipient', hoverLabel: 'Daniele Tomboro', onClick: () => setActiveStep(2) },
            { label: 'Review', hoverLabel: 'Antonio Dozortevo', onClick: () => setActiveStep(3) },
            {
              label: 'Pay',
              hoverLabel: 'Enrico Gusso II',
              onClick: () => setActiveStep(4),
            },
          ]}
          onClose={args.showCloseButton ? () => setClosed(true) : undefined}
          onGoBack={
            args.showMobileBackButton
              ? () => setActiveStep(activeStep - 1 > 0 ? activeStep - 1 : 0)
              : undefined
          }
        />

        {/* Instance of always `done` FlowNav for visual testing */}
        <FlowNavigation
          done
          avatar={<AvatarView imgSrc={args.avatarURL} profileType={args.profileType} />}
          activeStep={activeStep}
          steps={[
            { label: 'Recipient', hoverLabel: 'Daniele Tomboro', onClick: () => setActiveStep(0) },
            { label: 'Review', hoverLabel: 'Antonio Dozortevo', onClick: () => setActiveStep(1) },
            { label: 'Pay', hoverLabel: 'Enrico Gusso', onClick: () => setActiveStep(2) },
          ]}
          onClose={args.showCloseButton ? () => setClosed(true) : undefined}
          onGoBack={
            args.showMobileBackButton
              ? () => setActiveStep(activeStep - 1 > 0 ? activeStep - 1 : 0)
              : undefined
          }
        />

        <Body className="text-xs-center m-a-3">Content to test that the flow nav is centred</Body>

        <Button
          className="m-t-2"
          disabled={activeStep === 4}
          onClick={() => setActiveStep(activeStep + 1)}
        >
          Next Step
        </Button>
      </>
    );
  },
};

export const SendFlow: Story = {
  args: {
    profileType: ProfileType.PERSONAL,
    showCloseButton: true,
    showMobileBackButton: true,
    done: false,
    avatarURL: '../tapestry-01.png',
  },
  parameters: {
    padding: '0',
  },
  render: (args) => {
    const [activeStep, setActiveStep] = useState(2);
    const steps = [
      {
        label: 'Recipient',
        onClick: handleStepClick(0),
      },
      {
        label: 'Amount',
        hoverLabel: (
          <>
            You send 100 GBP <br />
            You get 99.39 GBP{' '}
          </>
        ),
        ...(activeStep > 1 && { onClick: handleStepClick(1) }),
      },
      {
        label: 'Review',
        ...(activeStep > 2 && { onClick: handleStepClick(2) }),
      },
      {
        label: 'Pay',
        ...(activeStep > 3 && { onClick: handleStepClick(3) }),
      },
    ];
    function handleStepClick(step: number) {
      return () => {
        setActiveStep(step);
      };
    }
    return (
      <>
        <FlowNavigation
          avatar={<AvatarView />}
          logo={<Logo />}
          activeStep={activeStep}
          steps={steps}
          onClose={() => alert('close & move away')}
          onGoBack={() => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)}
        />
        <Container size="narrow">
          <Body className="m-a-3">
            <Display type={Typography.DISPLAY_SMALL}>{steps[activeStep].label} Step</Display>
            <br />
            {lorem10}
          </Body>
        </Container>

        <Sticky>
          <Container
            size="narrow"
            className="d-flex justify-content-center align-items-center p-y-3"
          >
            <Button
              v2
              disabled={activeStep === 3}
              block
              onClick={() => setActiveStep(activeStep + 1)}
            >
              Continue
            </Button>
          </Container>
        </Sticky>
      </>
    );
  },
};

export const WithOverlayHeaderComparison: Story = {
  args: {
    profileType: ProfileType.PERSONAL,
    showCloseButton: true,
    showMobileBackButton: true,
    done: false,
    avatarURL: '../tapestry-01.png',
  },
  parameters: {
    padding: '0',
  },
  render: (args) => {
    const [activeStep, setActiveStep] = useState(4);
    const [closed, setClosed] = useState(false);
    if (closed) return <></>;
    return (
      <>
        <div style={{ border: '1px solid #e8e8e8' }}>
          <FlowNavigation
            avatar={args.profileType ? <AvatarView profileType={args.profileType} /> : null}
            activeStep={activeStep}
            done={args.done}
            steps={[]}
            onClose={args.showCloseButton ? () => setClosed(true) : undefined}
            onGoBack={
              args.showMobileBackButton
                ? () => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)
                : undefined
            }
          />
        </div>
        <div style={{ border: '1px solid #e8e8e8' }}>
          <OverlayHeader
            avatar={args.profileType ? <AvatarView profileType={args.profileType} /> : null}
            onClose={args.showCloseButton ? () => setClosed(true) : undefined}
          />
        </div>
      </>
    );
  },
};

export const ComposableVariant: Story = {
  args: {
    profileType: ProfileType.PERSONAL,
    showCloseButton: true,
    showMobileBackButton: true,
    done: false,
    avatarURL: '../tapestry-01.png',
  },
  parameters: {
    padding: '0',
    chromatic: {
      viewports,
    },
  },
  render: (args) => {
    const [activeStep, setActiveStep] = useState(2);
    const steps = [
      {
        label: 'Recipient',
        onClick: () => setActiveStep(0),
      },
      {
        label: 'Amount',
        hoverLabel: (
          <>
            You send 100 GBP <br />
            You get 99.39 GBP{' '}
          </>
        ),
        ...(activeStep > 1 && { onClick: () => setActiveStep(1) }),
      },
      {
        label: 'Review',
        ...(activeStep > 2 && { onClick: () => setActiveStep(2) }),
      },
      {
        label: 'Pay',
        ...(activeStep > 3 && { onClick: () => setActiveStep(3) }),
      },
    ];
    return (
      <>
        <FlowNavigation
          composable
          avatar={<AvatarView profileType={args.profileType} />}
          logo={<Logo />}
          activeStep={activeStep}
          steps={steps}
          onClose={args.showCloseButton ? () => alert('close') : undefined}
          onGoBack={
            args.showMobileBackButton
              ? () => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)
              : undefined
          }
        />
        <Container size="narrow">
          <Body className="m-a-3">
            <Display type={Typography.DISPLAY_SMALL}>{steps[activeStep].label} Step</Display>
            <br />
            {lorem10}
          </Body>
        </Container>

        <Sticky>
          <Container
            size="narrow"
            className="d-flex justify-content-center align-items-center p-y-3"
          >
            <Button
              v2
              disabled={activeStep === 3}
              block
              onClick={() => setActiveStep(activeStep + 1)}
            >
              Continue
            </Button>
          </Container>
        </Sticky>
      </>
    );
  },
};

export const WithoutStepper: Story = {
  args: {
    profileType: ProfileType.PERSONAL,
    showCloseButton: true,
    avatarURL: '../tapestry-01.png',
  },
  parameters: {
    chromatic: {
      viewports,
    },
  },
  render: (args) => {
    const [closed, setClosed] = useState(false);

    if (closed) return <Body className="text-xs-center m-a-3">FlowNavigation closed</Body>;

    return (
      <FlowNavigation
        avatar={<AvatarView profileType={args.profileType} />}
        logo={<Logo />}
        onClose={args.showCloseButton ? () => setClosed(true) : undefined}
      />
    );
  },
};

export const BorderControl: Story = {
  args: {
    profileType: ProfileType.PERSONAL,
    avatarURL: '../tapestry-01.png',
  },
  parameters: {
    chromatic: {
      viewports,
    },
  },
  render: (args) => {
    const [activeStep, setActiveStep] = useState(2);

    const steps = [
      {
        label: 'Recipient',
        onClick: () => setActiveStep(0),
      },
      {
        label: 'Amount',
        hoverLabel: (
          <>
            You send 100 GBP <br />
            You get 99.39 GBP{' '}
          </>
        ),
        ...(activeStep > 1 && { onClick: () => setActiveStep(1) }),
      },
      {
        label: 'Review',
        ...(activeStep > 2 && { onClick: () => setActiveStep(2) }),
      },
      {
        label: 'Pay',
        ...(activeStep > 3 && { onClick: () => setActiveStep(3) }),
      },
    ];

    return (
      <>
        <Body className="text-xs-center m-b-3">
          <Display type={Typography.DISPLAY_SMALL}>Non-composable Variant</Display>
          <br />
          Border controlled by <code>done</code> property only
        </Body>

        {/* Non-composable: done=false - SHOWS BORDER */}
        <FlowNavigation
          avatar={<AvatarView profileType={args.profileType} />}
          logo={<Logo />}
          activeStep={activeStep}
          done={false}
          steps={steps}
          onClose={() => {}}
          onGoBack={() => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)}
        />
        <Body className="text-xs-center m-b-3">
          <code>done=false</code> → ✅ Border shown
        </Body>

        {/* Non-composable: done=true - HIDES BORDER */}
        <FlowNavigation
          avatar={<AvatarView profileType={args.profileType} />}
          logo={<Logo />}
          activeStep={activeStep}
          done
          steps={steps}
          onClose={() => {}}
          onGoBack={() => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)}
        />
        <Body className="text-xs-center m-b-5">
          <code>done=true</code> → ❌ Border hidden
        </Body>

        <Body className="text-xs-center m-b-3 m-t-5">
          <Display type={Typography.DISPLAY_SMALL}>Composable Variant</Display>
          <br />
          Border ignores <code>done</code>, follows <code>showBottomBorder</code> only
        </Body>

        {/* Composable: showBottomBorder=true, done=false - SHOWS BORDER */}
        <FlowNavigation
          composable
          avatar={<AvatarView profileType={args.profileType} />}
          logo={<Logo />}
          activeStep={activeStep}
          done={false}
          steps={steps}
          showBottomBorder
          onClose={() => {}}
          onGoBack={() => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)}
        />
        <Body className="text-xs-center m-b-3">
          <code>showBottomBorder=true, done=false</code> → ✅ Border shown
        </Body>

        {/* Composable: showBottomBorder=true, done=true - SHOWS BORDER */}
        <FlowNavigation
          composable
          avatar={<AvatarView profileType={args.profileType} />}
          logo={<Logo />}
          activeStep={activeStep}
          done
          steps={steps}
          showBottomBorder
          onClose={() => {}}
          onGoBack={() => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)}
        />
        <Body className="text-xs-center m-b-3">
          <code>showBottomBorder=true, done=true</code> → ✅ Border shown (ignores done)
        </Body>

        {/* Composable: showBottomBorder=false, done=false - HIDES BORDER */}
        <FlowNavigation
          composable
          avatar={<AvatarView profileType={args.profileType} />}
          logo={<Logo />}
          activeStep={activeStep}
          done={false}
          steps={steps}
          showBottomBorder={false}
          onClose={() => {}}
          onGoBack={() => setActiveStep(activeStep > 0 ? activeStep - 1 : 0)}
        />
        <Body className="text-xs-center m-b-3">
          <code>showBottomBorder=false, done=false</code> → ❌ Border hidden
        </Body>
      </>
    );
  },
};
