import { Alert, Button, Empty, Flex, Skeleton, Typography } from 'antd';
import type { ButtonProps, SkeletonProps } from 'antd';
import type { ReactNode } from 'react';
import './StateKit.css';

const { Paragraph, Text, Title } = Typography;

export type EmptyStateProps = {
  title: ReactNode;
  description?: ReactNode;
  actionLabel?: ReactNode;
  onAction?: ButtonProps['onClick'];
  extra?: ReactNode;
};

export type ErrorStateProps = {
  title?: ReactNode;
  message: ReactNode;
  retryLabel?: ReactNode;
  onRetry?: ButtonProps['onClick'];
  extra?: ReactNode;
};

export type LoadingStateVariant = 'card' | 'list' | 'body';

export type LoadingStateProps = {
  variant?: LoadingStateVariant;
  rows?: number;
  active?: boolean;
};

export function EmptyState({
  title,
  description,
  actionLabel,
  onAction,
  extra,
}: EmptyStateProps) {
  return (
    <Empty
      image={Empty.PRESENTED_IMAGE_SIMPLE}
      description={
        <Flex vertical gap={4} align="center">
          <Text strong>{title}</Text>
          {description ? <Paragraph type="secondary">{description}</Paragraph> : null}
        </Flex>
      }
    >
      {actionLabel ? (
        <Button type="primary" onClick={onAction}>
          {actionLabel}
        </Button>
      ) : null}
      {extra}
    </Empty>
  );
}

export function ErrorState({
  title = '처리 중 문제가 발생했습니다.',
  message,
  retryLabel = '다시 시도',
  onRetry,
  extra,
}: ErrorStateProps) {
  return (
    <Alert
      type="error"
      showIcon
      message={title}
      description={
        <Flex vertical gap={12} align="flex-start">
          <Text>{message}</Text>
          <Flex gap={8} wrap="wrap">
            {onRetry ? <Button onClick={onRetry}>{retryLabel}</Button> : null}
            {extra}
          </Flex>
        </Flex>
      }
    />
  );
}

function resolveLoadingProps(variant: LoadingStateVariant): SkeletonProps {
  if (variant === 'list') {
    return {
      title: false,
      paragraph: { rows: 1 },
    };
  }

  if (variant === 'body') {
    return {
      title: true,
      paragraph: { rows: 5 },
    };
  }

  return {
    title: true,
    paragraph: { rows: 3 },
  };
}

export function LoadingState({
  variant = 'card',
  rows = variant === 'list' ? 4 : 1,
  active = true,
}: LoadingStateProps) {
  const skeletonProps = resolveLoadingProps(variant);

  return (
    <Flex vertical gap={variant === 'list' ? 8 : 16}>
      {Array.from({ length: rows }, (_, index) => (
        <div key={index} className={`state-kit-loading state-kit-loading--${variant}`}>
          <Skeleton active={active} {...skeletonProps} />
        </div>
      ))}
    </Flex>
  );
}

export function StateKitIntro() {
  return (
    <Flex vertical gap={4}>
      <Title level={5}>State Kit</Title>
      <Text type="secondary">빈 상태, 오류, 로딩 상태를 같은 규칙으로 조립합니다.</Text>
    </Flex>
  );
}
