<?php

declare(strict_types=1);

namespace App\Framework\Console\Layout;

final readonly class ResponsiveTable
{
    /**
     * @param array<string> $headers
     * @param array<array<string>> $rows
     * @param TerminalSize $terminalSize
     */
    public function __construct(
        public array $headers,
        public array $rows,
        public TerminalSize $terminalSize
    ) {
    }

    public function render(): array
    {
        $breakpoint = $this->terminalSize->getBreakpoint();
        $maxWidth = $this->terminalSize->getUsableWidth();

        if ($breakpoint->shouldTruncateText()) {
            return $this->renderCompact($breakpoint);
        }

        return $this->renderFull($maxWidth);
    }

    private function renderCompact(TerminalBreakpoint $breakpoint): array
    {
        $lines = [];
        $maxTextLength = $breakpoint->getMaxTextLength();

        // For very small terminals, show key-value pairs instead of table
        if ($breakpoint === TerminalBreakpoint::EXTRA_SMALL) {
            foreach ($this->rows as $index => $row) {
                $lines[] = "=== Row " . ($index + 1) . " ===";
                foreach ($this->headers as $i => $header) {
                    $value = $row[$i] ?? '';
                    $truncatedValue = $this->truncateText($value, $maxTextLength);
                    $lines[] = "{$header}: {$truncatedValue}";
                }
                $lines[] = '';
            }

            return $lines;
        }

        // For small terminals, show simplified table
        $columnWidths = $this->calculateCompactColumnWidths($breakpoint);

        // Header
        $headerLine = '';
        foreach ($this->headers as $i => $header) {
            $width = $columnWidths[$i] ?? 15;
            $headerLine .= str_pad(substr($header, 0, $width), $width) . ' ';
        }
        $lines[] = trim($headerLine);
        $lines[] = str_repeat('-', min(strlen($headerLine), $maxTextLength));

        // Rows
        foreach ($this->rows as $row) {
            $rowLine = '';
            foreach ($row as $i => $cell) {
                $width = $columnWidths[$i] ?? 15;
                $truncatedCell = $this->truncateText($cell, $width);
                $rowLine .= str_pad($truncatedCell, $width) . ' ';
            }
            $lines[] = trim($rowLine);
        }

        return $lines;
    }

    private function renderFull(int $maxWidth): array
    {
        $lines = [];
        $columnWidths = $this->calculateColumnWidths($maxWidth);

        // Header
        $headerLine = '';
        $separatorLine = '';
        foreach ($this->headers as $i => $header) {
            $width = $columnWidths[$i];
            $headerLine .= str_pad($header, $width) . ' | ';
            $separatorLine .= str_repeat('-', $width) . '-+-';
        }

        $lines[] = trim($headerLine, ' | ');
        $lines[] = trim($separatorLine, '-+-');

        // Rows
        foreach ($this->rows as $row) {
            $rowLine = '';
            foreach ($row as $i => $cell) {
                $width = $columnWidths[$i];
                $truncatedCell = $this->truncateText($cell, $width);
                $rowLine .= str_pad($truncatedCell, $width) . ' | ';
            }
            $lines[] = trim($rowLine, ' | ');
        }

        return $lines;
    }

    private function calculateColumnWidths(int $maxWidth): array
    {
        $columnCount = count($this->headers);
        $separatorSpace = ($columnCount - 1) * 3; // ' | ' between columns
        $availableWidth = $maxWidth - $separatorSpace;

        // Calculate minimum widths based on headers
        $minWidths = array_map('strlen', $this->headers);

        // Calculate preferred widths based on content
        $preferredWidths = $minWidths;
        foreach ($this->rows as $row) {
            foreach ($row as $i => $cell) {
                $preferredWidths[$i] = max($preferredWidths[$i], strlen($cell));
            }
        }

        // If preferred widths fit, use them
        $totalPreferred = array_sum($preferredWidths);
        if ($totalPreferred <= $availableWidth) {
            return $preferredWidths;
        }

        // Otherwise, distribute available width proportionally
        $weights = [];
        foreach ($preferredWidths as $i => $width) {
            $weights[$i] = $width / $totalPreferred;
        }

        $finalWidths = [];
        foreach ($weights as $i => $weight) {
            $finalWidths[$i] = max($minWidths[$i], (int) ($availableWidth * $weight));
        }

        return $finalWidths;
    }

    private function calculateCompactColumnWidths(TerminalBreakpoint $breakpoint): array
    {
        $maxWidth = $breakpoint->getTableWidth();
        $columnCount = count($this->headers);
        $baseWidth = (int) ($maxWidth / $columnCount);

        return array_fill(0, $columnCount, max(10, $baseWidth));
    }

    private function truncateText(string $text, int $maxLength): string
    {
        if (strlen($text) <= $maxLength) {
            return $text;
        }

        return substr($text, 0, $maxLength - 3) . '...';
    }

    public static function create(array $headers, array $rows, ?TerminalSize $terminalSize = null): self
    {
        return new self(
            $headers,
            $rows,
            $terminalSize ?? TerminalSize::detect()
        );
    }
}
