<?php

namespace App\Filament\Resources\CustomerResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;

class DocumentsRelationManager extends RelationManager
{
    protected static string $relationship = 'documents';
    protected static ?string $title = 'اسناد و مدارک';
    protected static ?string $modelLabel = 'سند';
    protected static ?string $pluralModelLabel = 'اسناد';

    public function form(Form $form): Form
    {
        return $form->schema([
            Forms\Components\TextInput::make('title')->label('عنوان سند')->required(),
            Forms\Components\Select::make('type')->label('نوع سند')->options([
                'contract' => 'قرارداد', 'identity' => 'مدارک هویتی', 'license' => 'مجوز',
                'insurance' => 'بیمه‌نامه', 'other' => 'سایر',
            ])->default('other')->required(),
            Forms\Components\DatePicker::make('expires_at')->label('تاریخ انقضا')->jalali(),
            Forms\Components\FileUpload::make('file_path')->label('فایل')
                ->disk('public')->directory('customer-docs')->downloadable()->openable()->webp()->required()->columnSpanFull(),
        ])->columns(3);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('title')
            ->columns([
                Tables\Columns\TextColumn::make('title')->label('عنوان'),
                Tables\Columns\TextColumn::make('type')->label('نوع')->badge()
                    ->formatStateUsing(fn ($state) => [
                        'contract' => 'قرارداد', 'identity' => 'مدارک هویتی', 'license' => 'مجوز',
                        'insurance' => 'بیمه‌نامه', 'other' => 'سایر',
                    ][$state] ?? $state),
                Tables\Columns\TextColumn::make('expires_at')->label('انقضا')->jalaliDate()
                    ->color(fn ($record) => $record->expires_at && $record->expires_at->isPast() ? 'danger'
                        : ($record->expires_at && $record->expires_at->lte(now()->addDays(30)) ? 'warning' : null)),
            ])
            ->headerActions([Tables\Actions\CreateAction::make()->label('افزودن سند')])
            ->actions([
                Tables\Actions\Action::make('download')->label('دانلود')->icon('heroicon-o-arrow-down-tray')
                    ->url(fn ($record) => asset('storage/' . $record->file_path))->openUrlInNewTab(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ]);
    }
}
