// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import { Text } from "@coreai-ds/react-components";
import { ArrowUpRegular } from "@fluentui/react-icons";
import * as React from 'react';
import { makeStyles } from "@coreai-ds/react-components";
import { tokens } from "@coreai-ds/react-components";
import { Card } from "@coreai-ds/react-components";
import { CardHeader } from "@coreai-ds/react-components";
import { Badge } from "@coreai-ds/react-components";
import { Divider } from "@coreai-ds/react-components";
import { mergeClasses } from "@coreai-ds/react-components";
import { Button } from "@coreai-ds/react-components";
import { CodeRegular } from "@fluentui/react-icons";
import { Link } from "@coreai-ds/react-components";

interface EmptyStateProps {
    /** Optional Illicon or custom artwork displayed above the message. */
    illustration?: React.ReactNode;
    /** Main empty-state heading. */
    header: React.ReactNode;
    /** Optional supporting text explaining the state or the next step. */
    description?: React.ReactNode;
    /** Optional row of value propositions, metrics, or highlights. */
    metrics?: React.ReactNode;
    /** Optional row of cards, choices, integrations, or detailed content. */
    cards?: React.ReactNode;
    /** Optional row of primary and secondary actions. */
    actions?: React.ReactNode;
    /** Optional supporting links displayed after the actions. */
    links?: React.ReactNode;
}

const useEmptyStateStyles = makeStyles({
    root: {
        boxSizing: 'border-box',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        rowGap: tokens.spacingVerticalXL,
        width: '100%',
        minHeight: '400px', // no dimension token; preserves the empty-state canvas height
        paddingBlock: tokens.spacingVerticalXXXL,
        paddingInline: tokens.spacingHorizontalXXL,
        textAlign: 'center',
    },
    illustration: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: tokens.colorNeutralForeground3,
        fontSize: tokens.fontSizeHero800,
        lineHeight: 1,
    },
    copy: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        rowGap: tokens.spacingVerticalXS,
        maxWidth: '600px', // no dimension token; matches the Figma copy width
    },
    header: {
        marginBlock: 0,
    },
    description: {
        marginBlock: 0,
    },
    collection: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'center',
        gap: tokens.spacingHorizontalL,
        width: '100%',
    },
    actions: {
        display: 'flex',
        flexWrap: 'wrap',
        alignItems: 'center',
        justifyContent: 'center',
        gap: tokens.spacingHorizontalS,
        width: '100%',
    },
    links: {
        display: 'flex',
        flexWrap: 'wrap',
        alignItems: 'center',
        justifyContent: 'center',
        gap: tokens.spacingHorizontalS,
    },
});

function EmptyState({ illustration, header, description, metrics, cards, actions, links, }: EmptyStateProps) {
    const styles = useEmptyStateStyles();
    return (<div className={styles.root}>
      {illustration ? <div className={styles.illustration}>{illustration}</div> : null}

      <div className={styles.copy}>
        <Text as="h2" preset="heading4" foreground={1} className={styles.header}>
          {header}
        </Text>
        {description ? (<Text as="p" preset="body" foreground={2} className={styles.description}>
            {description}
          </Text>) : null}
      </div>

      {metrics ? <div className={styles.collection}>{metrics}</div> : null}
      {cards ? <div className={styles.collection}>{cards}</div> : null}
      {actions ? <div className={styles.actions}>{actions}</div> : null}
      {links ? <div className={styles.links}>{links}</div> : null}
    </div>);
}

type DetailsItem = {
    key: React.Key;
    label: React.ReactNode;
    /** The value to show. If there is no value, leave this detail out of the list. */
    value: React.ReactNode;
};

interface DetailsListProps extends Omit<React.ComponentPropsWithoutRef<'dl'>, 'children'> {
    items: DetailsItem[];
    itemClassName?: string;
    labelClassName?: string;
    valueClassName?: string;
}

// ─── Styles ──────────────────────────────────────────────────────────────────
const useStyles = makeStyles({
    // ── Root container ─────────────────────────────────────────────────────────
    root: {
        display: 'flex',
        flexDirection: 'column',
        rowGap: tokens.spacingVerticalL,
        margin: 0,
        padding: 0,
        width: '100%',
    },
    // ── Row layout ─────────────────────────────────────────────────────────────
    item: {
        display: 'flex',
        flexDirection: 'column',
        rowGap: tokens.spacingVerticalXXS,
    },
    // ── Label / value text ────────────────────────────────────────────────────
    label: {
        margin: 0,
    },
    value: {
        margin: 0,
    },
});

// ─── Component ────────────────────────────────────────────────────────────────
function DetailsList({ items, className, itemClassName, labelClassName, valueClassName, ...rest }: DetailsListProps) {
    const styles = useStyles();
    return (<dl {...rest} className={mergeClasses('fui-DetailsList', styles.root, className)}>
      {items.map((item) => (<div key={item.key} className={mergeClasses('fui-DetailsList__item', styles.item, itemClassName)}>
          <dt className={mergeClasses('fui-DetailsList__label', styles.label, labelClassName)}>
            {typeof item.label === 'string' || typeof item.label === 'number' ? (<Text preset="bodySStrong" foreground={2}>
                {item.label}
              </Text>) : (item.label)}
          </dt>
          <dd className={mergeClasses('fui-DetailsList__value', styles.value, valueClassName)}>
            {typeof item.value === 'string' || typeof item.value === 'number' ? (<Text preset="body" foreground={1}>
                {item.value}
              </Text>) : (item.value)}
          </dd>
        </div>))}
    </dl>);
}

export const WithDetailCards = () => {
    const options = [
        { label: 'Before', isUpsell: false },
        { label: 'Upsell', isUpsell: true },
    ].map((option) => ({
        ...option,
        items: ['first', 'second', 'third'].map((key) => ({
            key,
            label: <Text preset="bodyS">Primary text slot</Text>,
            value: (<span className="empty-state-details-example__value">
            <Text preset="bodyS" foreground={3}>
              00:00 AM
            </Text>
            {option.isUpsell && (<Text preset="bodyS" className="empty-state-details-example__improvement" aria-label="97% increase">
                <ArrowUpRegular aria-hidden="true"/>
                97%
              </Text>)}
          </span>),
        })),
    }));
    const styles = /* css */ `
      .empty-state-details-example__card {
        box-sizing: border-box;
        flex: 0 0 auto;
        width: 392px;
        max-width: 100%;
        height: 197px;
        gap: var(--spacingVerticalS);
        padding: var(--spacingVerticalL) var(--spacingHorizontalL);
        text-align: left;
      }

      .empty-state-details-example__list {
        row-gap: var(--spacingVerticalS);
        line-height: var(--lineHeightBase200);
      }

      .empty-state-details-example__card--upsell {
        border-color: var(--colorBrandStroke1);
      }

      .empty-state-details-example__value {
        display: flex;
        align-items: center;
        gap: var(--spacingHorizontalM);
      }

      .empty-state-details-example__improvement {
        display: inline-flex;
        align-items: center;
        gap: var(--spacingHorizontalXXS);
        color: var(--colorStatusSuccessForeground1);
      }

      .empty-state-details-example__row {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        gap: var(--spacingHorizontalM);
      }

      .empty-state-details-example__header {
        row-gap: var(--spacingVerticalXXS);
      }

      .empty-state-details-example__option {
        white-space: nowrap;
      }
    `;
    return (<>
        <style>{styles}</style>
        <EmptyState header="Benefit from Action Artifact" cards={<>
              {options.map(({ label, isUpsell, items }) => (<Card className={`empty-state-details-example__card${isUpsell ? ' empty-state-details-example__card--upsell' : ''}`} key={label}>
                  <CardHeader className="empty-state-details-example__header" header={<Text preset="heading5" foreground={1}>
                        Card title
                      </Text>} description={<Text preset="bodyS">Additional metadata</Text>} action={<Badge appearance="tint" color={isUpsell ? 'brand' : 'subtle'} shape="rounded" className="empty-state-details-example__option">
                        {label}
                      </Badge>}/>
                  <Divider />
                  <DetailsList items={items} className="empty-state-details-example__list" itemClassName="empty-state-details-example__row"/>
                </Card>))}
            </>} actions={<>
              <Button appearance="primary">Action</Button>
              <Button icon={<CodeRegular />}>Action in code</Button>
            </>} links={<Link href="#">How to make the coolest artifact ever</Link>}/>
      </>);
};

export default WithDetailCards;
