<?php

namespace App\Livewire;

use Filament\Actions\Action;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Actions\Contracts\HasActions;
use Filament\Schemas\Concerns\InteractsWithSchemas;
use Filament\Schemas\Concerns\RestrictsFileUploadsToSchemaComponents;
use Filament\Schemas\Contracts\HasSchemas;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Livewire\Component;

class BoardDispatcher extends Component implements HasActions, HasSchemas, HasTable
{

    use InteractsWithActions;
    use InteractsWithSchemas;
    use InteractsWithTable;
    use RestrictsFileUploadsToSchemaComponents;

    public array $filters = [];
    public array $lists = [];
    public array $results = [];
    public array $destLabels = ['DR', 'MR', 'RW', 'DC', 'DM', 'MC', 'AM', 'SW', 'DC', 'DM', 'MC', 'AM', 'SM', 'ST', 'DC', 'DM', 'MC', 'AM', 'DL', 'ML', 'LM'];
    public string $boardVersion = '';
    public bool $copyDisabled = true;
    public bool $calculationDisabled = true;
    public string $calculationColor = 'gray';
    public string $copyColor = 'gray';

    public function mount(array $filters)
    {
        $this->boardVersion = uniqid();

        $this->filters = $filters;

        $active = [2, 4, 6, 9, 10, 11, 12, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 30, 32, 34];

        for ($i = 1; $i <= 35; $i++) {
            if (in_array($i, $active))
                $this->lists["dest-{$i}"] = [];
            else
                $this->lists["blind-{$i}"] = [];
        }
    }

    /*
            'id' => $player_id,
            'name' => $val['player_name'],
            'preferred_foot' => $val['preferred_foot'],
            'player_position' => $player_position,
            'player_color' => $player_color,
            'timed_color' => $timed_color,
            'events_played' => $events_played,
            'everage_minutes' => $everage_minutes,
        */
    public function table(Table $table): Table
    {
        return $table
            ->headerActions([
                Action::make('Close')->icon('phosphor-x')->close()
            ])
            ->records(fn(): array => PlayerCalculator::load($this->filters))
            ->paginated(false)
            ->striped()
            ->columns([
                TextColumn::make('name')
                    ->sortable()
                    // ->searchable()
                    ->icon('icon-soccerplayer')
                    ->extraAttributes(fn($record) => [
                        'data-id' => $record['id'],
                        'class' => 'sortable-zone',
                        'style' => 'padding: 4px !important; cursor:pointer; user-select: none;',
                        'wire:key' => "item-src-" . $record['id'] . "-v-" . $this->boardVersion
                    ]),
            ])
            ->filters([
                // ...
            ])
            ->recordActions([
                // ...
            ])
            ->toolbarActions([
                // ...
            ]);
    }

    public function render()
    {
        return view('livewire.board-dispatcher');
    }


    public function setCalculationButton()
    {
        $count = 1;
        for ($i = 1; $i <= 35; $i++) {
            $bayKey = "dest-{$i}";

            if (isset($this->lists[$bayKey]) && ! empty($this->lists[$bayKey])) {
                $count++;
            }
        }
        if ($count > 2) {
            $this->calculationDisabled = false;
            $this->calculationColor = 'info';
        } else {
            $this->calculationDisabled = true;
            $this->calculationColor = 'gray';
        }
    }

    public function setCopyButton()
    {
        if (\count($this->results) > 0) {
            $this->copyDisabled = false;
            $this->copyColor = 'info';
        } else {
            $this->copyDisabled = true;
            $this->copyColor = 'gray';
        }
    }

    public function calculate()
    {
        $this->results = [];
        for ($i = 1; $i <= 35; $i++) {
            $bayKey = "dest-{$i}";

            if (isset($this->lists[$bayKey]) && ! empty($this->lists[$bayKey])) {
                $this->results[] = $this->lists[$bayKey][0];
            }
        }

        $this->setCopyButton();
    }

    public function copyResult()
    {
        $copystring = '';
        foreach ($this->results as $row) {
            unset($row['origin']);
            unset($row['pcolor']);
            unset($row['ecolor']);
            unset($row['info']);
            $copystring .= implode("\t", $row) . "\n";
        }
        $this->js("navigator.clipboard.writeText(`$copystring`)");
    }


    public function moveItem($itemId, $fromList, $toList, $newIndex)
    {
        $itemId = (string) $itemId;
        $newIndex = (int) $newIndex;

        if (! $toList || $fromList === $toList || ! isset($this->lists[$fromList]) || ! isset($this->lists[$toList])) {
            $this->boardVersion = uniqid();

            return;
        }

        // Limit-Guard: Wenn das Ziel bereits ein Element enthält, abbrechen
        if (count($this->lists[$toList]) >= 1) {
            $this->boardVersion = uniqid();

            return;
        }

        $foundItem = null;

        foreach ($this->lists[$fromList] as $key => $item) {
            if ((string) $item['id'] === $itemId) {
                $item['position'] = $this->positions($toList);
                $foundItem = $item;
                unset($this->lists[$fromList][$key]);
                $this->lists[$fromList] = array_values($this->lists[$fromList]);
                break;
            }
        }

        if ($foundItem) {
            array_splice($this->lists[$toList], $newIndex, 0, [$foundItem]);
        }

        $this->setCalculationButton();

        $this->boardVersion = uniqid();
    }

    public function positions(string $pos)
    {
        $pos = (int) str_replace('dest-', '', $pos);
        $options = [2 => 'DR', 4 => 'MR', 6 => 'RW', 9 => 'DC', 10 => 'DM', 11 => 'MC', 12 => 'AM', 15 => 'SW', 16 => 'DC', 17 => 'DM', 18 => 'MC', 19 => 'AM', 20 => 'SM', 21 => 'ST', 23 => 'DC', 24 => 'DM', 25 => 'MC', 26 => 'AM', 30 => 'DL', 32 => 'ML', 34 => 'LM'];
        if (isset($options[$pos]))
            return $options[$pos];
        else
            return $pos;
    }

    public function returnToOrigin($itemId, $currentListId)
    {
        $itemId = (string) $itemId;

        // Log::info($this->boardVersion);
        // Log::info('itemId, currentListId', [$itemId, $currentListId]);
        // Log::info('OLD LIST', $this->lists);

        if (! isset($this->lists[$currentListId])) {
            $this->boardVersion = uniqid();

            return;
        }

        $foundItem = null;

        foreach ($this->lists[$currentListId] as $key => $item) {
            if ((string) $item['id'] === $itemId) {
                $foundItem = $item;
                unset($this->lists[$currentListId][$key]);
                $this->lists[$currentListId] = array_values($this->lists[$currentListId]);
                break;
            }
        }

        if ($foundItem && isset($this->lists[$foundItem['origin']])) {
            // Nur zurücklegen, wenn die Quelle wirklich frei ist
            array_unshift($this->lists[$foundItem['origin']], $foundItem);
            // if (count($this->lists[$foundItem['origin']]) < 2) {
            //     Log::info('origin');
            //     array_unshift($this->lists[$foundItem['origin']], $foundItem);
            // } else {
            //     // Ausfallsicherheit gegen Datenverlust: Zurück in die Bucht schieben
            //     array_unshift($this->lists[$currentListId], $foundItem);
            //     Log::info('box');
            // }
        }

        $this->setCalculationButton();

        $this->boardVersion = uniqid();
    }

    public function resetBoard()
    {
        // Alle 21 Zielbays durchlaufen
        for ($i = 1; $i <= 21; $i++) {
            $bayKey = "dest-{$i}";

            if (isset($this->lists[$bayKey]) && ! empty($this->lists[$bayKey])) {
                foreach ($this->lists[$bayKey] as $item) {
                    $targetOrigin = $item['origin'];

                    // Element zurück in sein Original-Quell-Tab schieben
                    if (isset($this->lists[$targetOrigin])) {
                        array_unshift($this->lists[$targetOrigin], $item);
                    }
                }

                // Die Zielbucht komplett leeren
                $this->lists[$bayKey] = [];
            }
        }

        // Falls Sie die boardVersion-Logik nutzen, erneuern wir sie hier für den DOM-Refresh:
        if (property_exists($this, 'boardVersion')) {
            $this->boardVersion = uniqid();
        }

        // Falls Sie die Javascript-Event/ignore-Logik nutzen, feuern wir das Refresh-Event:
        $this->dispatch('refreshBoard', lists: $this->lists);

        $this->results = [];

        $this->setCalculationButton();

        $this->setCopyButton();
    }
}
