import { ReactNode } from 'react';
import { Typography, Space, Breadcrumb, Grid } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { spacing } from '@/styles/designTokens';

const { Title, Text } = Typography;
const { useBreakpoint } = Grid;

export interface BreadcrumbItem {
  title: string;
  path?: string;
}

export interface PageHeaderProps {
  /** Page title */
  title: string;
  /** Optional subtitle or description */
  subtitle?: string;
  /** Breadcrumb items (path is optional for current page) */
  breadcrumbs?: BreadcrumbItem[];
  /** Extra content to render on the right side (buttons, filters, etc.) */
  extra?: ReactNode;
  /** Whether to show home in breadcrumbs */
  showHome?: boolean;
}

/**
 * Consistent page header component with title, breadcrumbs, and optional actions.
 *
 * @example
 * <PageHeader
 *   title="Kassekladde"
 *   subtitle="Opret og rediger kladde-posteringer"
 *   breadcrumbs={[{ title: 'Bogføring', path: '/bogforing' }, { title: 'Kassekladde' }]}
 *   extra={<Button type="primary">Ny postering</Button>}
 * />
 */
export function PageHeader({
  title,
  subtitle,
  breadcrumbs,
  extra,
  showHome = true,
}: PageHeaderProps) {
  const screens = useBreakpoint();
  const isMobile = !screens.md;

  const breadcrumbItems = breadcrumbs
    ? [
        ...(showHome
          ? [
              {
                title: (
                  <Link to="/">
                    <HomeOutlined />
                  </Link>
                ),
              },
            ]
          : []),
        ...breadcrumbs.map((item) => ({
          title: item.path ? <Link to={item.path}>{item.title}</Link> : item.title,
        })),
      ]
    : undefined;

  return (
    <div
      style={{
        marginBottom: spacing.lg,
      }}
    >
      {/* Breadcrumbs */}
      {breadcrumbItems && breadcrumbItems.length > 0 && (
        <Breadcrumb
          items={breadcrumbItems}
          style={{ marginBottom: spacing.sm }}
        />
      )}

      {/* Title row */}
      <div
        style={{
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
          justifyContent: 'space-between',
          alignItems: isMobile ? 'flex-start' : 'center',
          gap: isMobile ? spacing.sm : spacing.md,
        }}
      >
        <div>
          <Title level={isMobile ? 4 : 3} style={{ margin: 0 }}>
            {title}
          </Title>
          {subtitle && (
            <Text type="secondary" style={{ marginTop: spacing.xs }}>
              {subtitle}
            </Text>
          )}
        </div>

        {extra && (
          <Space wrap size="small">
            {extra}
          </Space>
        )}
      </div>
    </div>
  );
}

export default PageHeader;
