<?php

declare(strict_types=1);

namespace App\Framework\View\Table;

final readonly class TableColumn
{
    public function __construct(
        public string $key,
        public string $header,
        public ?string $cssClass = null,
        public ?CellFormatter $formatter = null,
        public bool $sortable = false,
        public ?string $width = null,
        public ?CellType $defaultType = null
    ) {
    }

    public function renderHeader(): string
    {
        $classString = $this->cssClass ? " class=\"{$this->cssClass}\"" : '';
        $styleString = $this->width ? " style=\"width: {$this->width}\"" : '';
        $sortableClass = $this->sortable ? ' sortable' : '';

        return "<th{$classString}{$styleString}><span class=\"header-content{$sortableClass}\">{$this->header}</span></th>";
    }

    public function createCell(mixed $value): TableCell
    {
        return new TableCell(
            value: $value,
            cssClass: $this->cssClass,
            type: $this->defaultType,
            formatter: $this->formatter
        );
    }

    public static function text(string $key, string $header, ?string $cssClass = null): self
    {
        return new self($key, $header, $cssClass, null, false, null, CellType::TEXT);
    }

    public static function sortable(string $key, string $header, ?string $cssClass = null): self
    {
        return new self($key, $header, $cssClass, null, true, null, CellType::TEXT);
    }

    public static function withFormatter(
        string $key,
        string $header,
        CellFormatter $formatter,
        ?string $cssClass = null
    ): self {
        return new self($key, $header, $cssClass, $formatter, false, null);
    }

    public static function boolean(string $key, string $header, ?string $cssClass = null): self
    {
        return new self($key, $header, $cssClass, null, false, null, CellType::BOOLEAN);
    }

    public static function email(string $key, string $header, ?string $cssClass = null): self
    {
        return new self($key, $header, $cssClass, null, false, null, CellType::EMAIL);
    }

    public static function url(string $key, string $header, ?string $cssClass = null): self
    {
        return new self($key, $header, $cssClass, null, false, null, CellType::URL);
    }
}
