<?php

namespace App\Filament\Employee\Pages;

use Filament\Forms;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class MyProfilePage extends Page implements HasForms
{
    use InteractsWithForms;

    protected static ?string $navigationIcon = 'heroicon-o-user-circle';
    protected static ?string $navigationLabel = 'Profil Saya';
    protected static ?string $title = 'Profil Saya';
    protected static ?string $slug = 'my-profile';
    protected static ?string $navigationGroup = 'Akun';
    protected static ?int $navigationSort = 100;

    protected static string $view = 'filament.employee.pages.my-profile-page';

    public ?array $profileData = [];
    public ?array $passwordData = [];
    public ?array $homeLocationData = [];

    public function mount(): void
    {
        $user = Auth::user();

        $this->profileForm->fill([
            'name' => $user->name,
            'email' => $user->email,
            'phone' => $user->phone,
            'address' => $user->address,
        ]);

        $this->homeLocationForm->fill([
            'home_latitude' => $user->home_latitude,
            'home_longitude' => $user->home_longitude,
        ]);
    }

    protected function getForms(): array
    {
        return [
            'profileForm',
            'passwordForm',
            'homeLocationForm',
        ];
    }

    public function profileForm(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Informasi Pribadi')
                    ->description('Perbarui informasi profil Anda')
                    ->schema([
                        Forms\Components\FileUpload::make('avatar')
                            ->label('Foto Profil')
                            ->image()
                            ->avatar()
                            ->disk('public_direct')
                            ->directory('avatars')
                            ->maxSize(2048)
                            ->circleCropper()
                            ->columnSpanFull(),
                        Forms\Components\TextInput::make('name')
                            ->label('Nama Lengkap')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\TextInput::make('email')
                            ->label('Email')
                            ->email()
                            ->disabled()
                            ->dehydrated(false)
                            ->helperText('Email tidak dapat diubah'),
                        Forms\Components\TextInput::make('phone')
                            ->label('Nomor Telepon')
                            ->tel()
                            ->maxLength(20),
                        Forms\Components\Textarea::make('address')
                            ->label('Alamat')
                            ->rows(3)
                            ->maxLength(500),
                    ])
                    ->columns(2),
            ])
            ->statePath('profileData');
    }

    public function passwordForm(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Ubah Password')
                    ->description('Pastikan menggunakan password yang kuat')
                    ->schema([
                        Forms\Components\TextInput::make('current_password')
                            ->label('Password Saat Ini')
                            ->password()
                            ->revealable()
                            ->required()
                            ->currentPassword(),
                        Forms\Components\TextInput::make('password')
                            ->label('Password Baru')
                            ->password()
                            ->revealable()
                            ->required()
                            ->minLength(8)
                            ->confirmed(),
                        Forms\Components\TextInput::make('password_confirmation')
                            ->label('Konfirmasi Password Baru')
                            ->password()
                            ->revealable()
                            ->required(),
                    ])
                    ->columns(1),
            ])
            ->statePath('passwordData');
    }

    public function homeLocationForm(Form $form): Form
    {
        $user = Auth::user();
        $company = $user->company;
        $canEdit = $company->allow_employee_edit_home_location || $user->hasRole(['admin', 'super_admin']);

        return $form
            ->schema([
                Forms\Components\Section::make('Lokasi Rumah (WFH)')
                    ->description($canEdit
                        ? 'Tentukan lokasi rumah Anda untuk keperluan Work From Home'
                        : 'Hubungi admin untuk mengubah lokasi rumah')
                    ->schema([
                        Forms\Components\TextInput::make('home_latitude')
                            ->label('Latitude')
                            ->numeric()
                            ->disabled(!$canEdit)
                            ->rules(['nullable', 'numeric', 'between:-90,90']),
                        Forms\Components\TextInput::make('home_longitude')
                            ->label('Longitude')
                            ->numeric()
                            ->disabled(!$canEdit)
                            ->rules(['nullable', 'numeric', 'between:-180,180']),
                        Forms\Components\Placeholder::make('map_info')
                            ->label('')
                            ->content(fn () => $user->home_latitude && $user->home_longitude
                                ? "Lokasi saat ini: {$user->home_latitude}, {$user->home_longitude}"
                                : 'Lokasi rumah belum diatur')
                            ->columnSpanFull(),
                    ])
                    ->columns(2)
                    ->visible($canEdit || ($user->home_latitude && $user->home_longitude)),
            ])
            ->statePath('homeLocationData');
    }

    public function updateProfile(): void
    {
        $data = $this->profileForm->getState();
        $user = Auth::user();

        // Handle avatar upload
        if (isset($data['avatar']) && $data['avatar']) {
            // Delete old avatar if exists
            if ($user->avatar && Storage::disk('public_direct')->exists($user->avatar)) {
                Storage::disk('public_direct')->delete($user->avatar);
            }
            $user->avatar = $data['avatar'];
        }

        $user->name = $data['name'];
        $user->phone = $data['phone'];
        $user->address = $data['address'];
        $user->save();

        Notification::make()
            ->title('Profil berhasil diperbarui')
            ->success()
            ->send();
    }

    public function updatePassword(): void
    {
        $data = $this->passwordForm->getState();
        $user = Auth::user();

        $user->password = Hash::make($data['password']);
        $user->save();

        $this->passwordForm->fill();

        Notification::make()
            ->title('Password berhasil diperbarui')
            ->success()
            ->send();
    }

    public function updateHomeLocation(): void
    {
        $user = Auth::user();
        $company = $user->company;

        // Check permission
        if (!$company->allow_employee_edit_home_location && !$user->hasRole(['admin', 'super_admin'])) {
            Notification::make()
                ->title('Tidak diizinkan')
                ->body('Fitur edit lokasi rumah tidak diaktifkan oleh admin')
                ->danger()
                ->send();
            return;
        }

        $data = $this->homeLocationForm->getState();

        $user->home_latitude = $data['home_latitude'];
        $user->home_longitude = $data['home_longitude'];
        $user->save();

        Notification::make()
            ->title('Lokasi rumah berhasil diperbarui')
            ->success()
            ->send();
    }

    public function getViewData(): array
    {
        $user = Auth::user();

        return [
            'user' => $user,
            'canEditHomeLocation' => $user->company->allow_employee_edit_home_location || $user->hasRole(['admin', 'super_admin']),
        ];
    }
}
