<?php

use App\Models\MailAccount;
use Livewire\Volt\Component;
use Illuminate\Support\Facades\Validator;
use Livewire\Attributes\Title;
use Livewire\Attributes\Validate;

new #[Title('Mail Settings')] class extends Component {
    public $mailAccounts = [];
    public $showForm = false;
    public $editingId = null;

    // Form fields
    public $name = '';
    public $email = '';
    public $imap_host = '';
    public $imap_port = 993;
    public $imap_encryption = 'ssl';
    public $imap_validate_cert = true;
    public $imap_username = '';
    public $imap_password = '';
    public $imap_protocol = 'imap';
    public $smtp_host = '';
    public $smtp_port = 587;
    public $smtp_encryption = 'tls';
    public $smtp_username = '';
    public $smtp_password = '';
    public $is_active = true;
    public $is_default = false;
    public $from_name = '';

    public function mount(): void
    {
        // Only superadmins can manage mail accounts
        if (!auth()->user()->hasRole('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        $this->loadMailAccounts();
    }

    public function loadMailAccounts(): void
    {
        $this->mailAccounts = MailAccount::orderBy('is_default', 'desc')->orderBy('name')->get();
    }

    public function createNew(): void
    {
        if (!auth()->user()->hasRole('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        $this->resetForm();
        $this->showForm = true;
        $this->editingId = null;
    }

    public function edit($id): void
    {
        if (!auth()->user()->hasRole('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        $account = MailAccount::findOrFail($id);

        $this->editingId = $account->id;
        $this->name = $account->name;
        $this->email = $account->email;
        $this->imap_host = $account->imap_host ?? '';
        $this->imap_port = $account->imap_port ?? 993;
        $this->imap_encryption = $account->imap_encryption ?? 'ssl';
        $this->imap_validate_cert = $account->imap_validate_cert ?? true;
        $this->imap_username = $account->imap_username ?? '';
        $this->imap_password = ''; // Don't populate password for security
        $this->imap_protocol = $account->imap_protocol ?? 'imap';
        $this->smtp_host = $account->smtp_host ?? '';
        $this->smtp_port = $account->smtp_port ?? 587;
        $this->smtp_encryption = $account->smtp_encryption ?? 'tls';
        $this->smtp_username = $account->smtp_username ?? '';
        $this->smtp_password = ''; // Don't populate password for security
        $this->is_active = $account->is_active;
        $this->is_default = $account->is_default;
        $this->from_name = $account->from_name ?? '';

        $this->showForm = true;
    }

    public function save(): void
    {
        if (!auth()->user()->hasRole('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        $validated = $this->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'imap_host' => 'nullable|string|max:255',
            'imap_port' => 'nullable|integer|min:1|max:65535',
            'imap_encryption' => 'nullable|in:ssl,tls,',
            'imap_validate_cert' => 'boolean',
            'imap_username' => 'nullable|string|max:255',
            'imap_password' => 'nullable|string|max:255',
            'imap_protocol' => 'nullable|in:imap,pop3',
            'smtp_host' => 'nullable|string|max:255',
            'smtp_port' => 'nullable|integer|min:1|max:65535',
            'smtp_encryption' => 'nullable|in:ssl,tls,',
            'smtp_username' => 'nullable|string|max:255',
            'smtp_password' => 'nullable|string|max:255',
            'is_active' => 'boolean',
            'is_default' => 'boolean',
            'from_name' => 'nullable|string|max:255',
        ]);

        if ($this->editingId) {
            $account = MailAccount::findOrFail($this->editingId);

            // Only update password if a new one is provided
            if (empty($validated['imap_password'])) {
                unset($validated['imap_password']);
            }
            if (empty($validated['smtp_password'])) {
                unset($validated['smtp_password']);
            }

            $account->update($validated);

            if ($this->is_default) {
                $account->setAsDefault();
            }

            session()->flash('message', 'Mail account updated successfully.');
        } else {
            $account = MailAccount::create($validated);

            if ($this->is_default) {
                $account->setAsDefault();
            }

            session()->flash('message', 'Mail account created successfully.');
        }

        $this->resetForm();
        $this->showForm = false;
        $this->loadMailAccounts();
    }

    public function delete($id): void
    {
        if (!auth()->user()->hasRole('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        $account = MailAccount::findOrFail($id);

        // Check if any departments are using this account
        if ($account->departments()->count() > 0) {
            session()->flash('error', 'Cannot delete mail account. It is being used by one or more departments.');
            return;
        }

        $account->delete();
        session()->flash('message', 'Mail account deleted successfully.');
        $this->loadMailAccounts();
    }

    public function cancel(): void
    {
        $this->resetForm();
        $this->showForm = false;
    }

    public function resetForm(): void
    {
        $this->editingId = null;
        $this->name = '';
        $this->email = '';
        $this->imap_host = '';
        $this->imap_port = 993;
        $this->imap_encryption = 'ssl';
        $this->imap_validate_cert = true;
        $this->imap_username = '';
        $this->imap_password = '';
        $this->imap_protocol = 'imap';
        $this->smtp_host = '';
        $this->smtp_port = 587;
        $this->smtp_encryption = 'tls';
        $this->smtp_username = '';
        $this->smtp_password = '';
        $this->is_active = true;
        $this->is_default = false;
        $this->from_name = '';
        $this->resetValidation();
    }

    public function setAsDefault($id): void
    {
        if (!auth()->user()->hasRole('superadmin')) {
            abort(403, 'Unauthorized action.');
        }

        $account = MailAccount::findOrFail($id);
        $account->setAsDefault();
        session()->flash('message', 'Default mail account updated successfully.');
        $this->loadMailAccounts();
    }
}; ?>

<section class="w-full">
    @include('partials.settings-heading')

    <x-settings.layout
        :heading="__('Mail Settings')"
        :subheading="__('Manage IMAP and SMTP mail accounts for sending and receiving emails')"
        :fullWidth="true">

        @if (session()->has('message'))
            <div class="mt-6 mb-3 bg-green-50 dark:bg-green-900 border-l-4 border-green-400 p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <svg class="h-5 w-5 text-green-400" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                        </svg>
                    </div>
                    <div class="ml-3">
                        <div class="text-sm text-green-700 dark:text-green-200">
                            <p class="font-semibold mb-3">Success</p>
                            <ul class="space-y-2.5">
                                <li class="flex items-start gap-2">
                                    <span class="leading-relaxed">{{ session('message') }}</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        @endif

        @if (session()->has('error'))
            <div class="mt-6 mt-3 bg-red-50 dark:bg-red-900 border-l-4 border-red-400 p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
                        </svg>
                    </div>
                    <div class="ml-3">
                        <div class="text-sm text-red-700 dark:text-red-200">
                            <p class="font-semibold mb-3">Error</p>
                            <ul class="space-y-2.5">
                                <li class="flex items-start gap-2">
                                    <span class="leading-relaxed">{{ session('error') }}</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        @endif

        @if (!$showForm)
            <div class="mb-6">
                <flux:button wire:click="createNew" variant="primary" icon="plus" class="!bg-indigo-700 hover:!bg-indigo-500 !text-white">
                    {{ __('Add Mail Account') }}
                </flux:button>
            </div>

            @if (count($mailAccounts) > 0)
                <div class="space-y-4">
                    @foreach ($mailAccounts as $account)
                        <div class="border dark:border-zinc-700 rounded-lg p-4 {{ $account->is_default ? 'border-indigo-500 dark:border-indigo-500' : '' }}">
                            <div class="flex justify-between items-start">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2">
                                        <h3 class="text-lg font-semibold dark:text-white">{{ $account->name }}</h3>
                                        @if ($account->is_default)
                                            <flux:badge variant="success">{{ __('Default') }}</flux:badge>
                                        @endif
                                        @if (!$account->is_active)
                                            <flux:badge variant="warning">{{ __('Inactive') }}</flux:badge>
                                        @endif
                                    </div>
                                    <p class="text-sm text-zinc-600 dark:text-zinc-400">{{ $account->email }}</p>

                                    <div class="mt-2 grid grid-cols-2 gap-4 text-sm">
                                        <div>
                                            <p class="font-medium dark:text-white">IMAP Settings</p>
                                            <p class="text-zinc-600 dark:text-zinc-400">{{ $account->imap_host ?? 'Not configured' }}</p>
                                            @if($account->imap_host)
                                                <p class="text-zinc-500 dark:text-zinc-500 text-xs">
                                                    {{ $account->imap_protocol }}://{{ $account->imap_host }}:{{ $account->imap_port }} ({{ $account->imap_encryption }})
                                                </p>
                                            @endif
                                        </div>
                                        <div>
                                            <p class="font-medium dark:text-white">SMTP Settings</p>
                                            <p class="text-zinc-600 dark:text-zinc-400">{{ $account->smtp_host ?? 'Not configured' }}</p>
                                            @if($account->smtp_host)
                                                <p class="text-zinc-500 dark:text-zinc-500 text-xs">
                                                    {{ $account->smtp_host }}:{{ $account->smtp_port }} ({{ $account->smtp_encryption }})
                                                </p>
                                            @endif
                                        </div>
                                    </div>
                                </div>

                                <div class="flex gap-2">
                                    @if (!$account->is_default)
                                        <flux:button wire:click="setAsDefault({{ $account->id }})" variant="ghost" size="sm">
                                            {{ __('Set as Default') }}
                                        </flux:button>
                                    @endif
                                    <flux:button wire:click="edit({{ $account->id }})" variant="ghost" size="sm">
                                        <x-lucide-pencil class="w-4 h-4" />
                                    </flux:button>
                                    <flux:button wire:click="delete({{ $account->id }})" wire:confirm="Are you sure you want to delete this mail account?" variant="ghost" size="sm" class="text-red-600 hover:text-red-800">
                                        <x-lucide-trash-2 class="w-4 h-4" />
                                    </flux:button>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            @else
                <div class="text-center py-12 border dark:border-zinc-700 rounded-lg">
                    <x-lucide-inbox class="w-12 h-12 mx-auto text-zinc-400 mb-4" />
                    <h3 class="text-lg font-semibold dark:text-white mb-2">{{ __('No mail accounts yet') }}</h3>
                    <p class="text-zinc-600 dark:text-zinc-400">{{ __('Get started by creating your first mail account') }}</p>
                </div>
            @endif
        @else
            <form wire:submit="save" class="space-y-6" id="mail-settings-form">
                <h3 class="text-lg font-semibold dark:text-white">
                    {{ $editingId ? __('Edit Mail Account') : __('Create Mail Account') }}
                </h3>

                <div class="grid grid-cols-2 gap-4">
                    <flux:input
                        wire:model="name"
                        :label="__('Account Name')"
                        :placeholder="__('e.g., Support Email')"
                        required
                    />
                    <flux:input
                        wire:model="email"
                        :label="__('Email Address')"
                        type="email"
                        :placeholder="__('support@example.com')"
                        required
                    />
                </div>

                <flux:input
                    wire:model="from_name"
                    :label="__('From Name (Display Name)')"
                    :placeholder="__('Support Team')"
                />

                <hr class="border-zinc-200 dark:border-zinc-700">

                <h4 class="text-md font-semibold dark:text-white">{{ __('IMAP Settings (Incoming Mail)') }}</h4>

                <div class="grid grid-cols-3 gap-4">
                    <div class="col-span-2">
                        <flux:input
                            wire:model="imap_host"
                            :label="__('IMAP Host')"
                            :placeholder="__('imap.example.com')"
                        />
                    </div>
                    <flux:input
                        wire:model="imap_port"
                        :label="__('Port')"
                        type="number"
                        :placeholder="__('993')"
                    />
                </div>

                <div class="grid grid-cols-3 gap-4">
                    <flux:select wire:model="imap_protocol" :label="__('Protocol')">
                        <option value="imap">IMAP</option>
                        <option value="pop3">POP3</option>
                    </flux:select>

                    <flux:select wire:model="imap_encryption" :label="__('Encryption')">
                        <option value="ssl">SSL</option>
                        <option value="tls">TLS</option>
                        <option value="">{{ __('None') }}</option>
                    </flux:select>

                    <div class="flex items-center pt-6">
                        <x-ticaga-checkbox
                            wire:model="imap_validate_cert"
                            :label="__('Validate Certificate')"
                        />
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <flux:input
                        wire:model="imap_username"
                        :label="__('IMAP Username')"
                        :placeholder="__('Usually same as email')"
                    />
                    <flux:input
                        wire:model="imap_password"
                        :label="__('IMAP Password')"
                        type="password"
                        :placeholder="$editingId ? __('Leave blank to keep current') : __('Enter password')"
                    />
                </div>

                <hr class="border-zinc-200 dark:border-zinc-700">

                <h4 class="text-md font-semibold dark:text-white">{{ __('SMTP Settings (Outgoing Mail)') }}</h4>

                <div class="grid grid-cols-3 gap-4">
                    <div class="col-span-2">
                        <flux:input
                            wire:model="smtp_host"
                            :label="__('SMTP Host')"
                            :placeholder="__('smtp.example.com')"
                        />
                    </div>
                    <flux:input
                        wire:model="smtp_port"
                        :label="__('Port')"
                        type="number"
                        :placeholder="__('587')"
                    />
                </div>

                <flux:select wire:model="smtp_encryption" :label="__('Encryption')">
                    <option value="tls">TLS</option>
                    <option value="ssl">SSL</option>
                    <option value="">{{ __('None') }}</option>
                </flux:select>

                <div class="grid grid-cols-2 gap-4">
                    <flux:input
                        wire:model="smtp_username"
                        :label="__('SMTP Username')"
                        :placeholder="__('Usually same as email')"
                    />
                    <flux:input
                        wire:model="smtp_password"
                        :label="__('SMTP Password')"
                        type="password"
                        :placeholder="$editingId ? __('Leave blank to keep current') : __('Enter password')"
                    />
                </div>

                <hr class="border-zinc-200 dark:border-zinc-700">

                <div class="flex flex-col gap-4">
                    <div>
                        <x-ticaga-checkbox
                            wire:model="is_active"
                            :label="__('Active')"
                        />
                        <p class="text-sm text-zinc-600 dark:text-zinc-400 ml-6">{{ __('Enable this account for sending and receiving emails') }}</p>
                    </div>
                    <div>
                        <x-ticaga-checkbox
                            wire:model="is_default"
                            :label="__('Set as Default')"
                        />
                        <p class="text-sm text-zinc-600 dark:text-zinc-400 ml-6">{{ __('Use this account as the default for all outgoing emails') }}</p>
                    </div>
                </div>

                <div class="flex items-center gap-4 pt-4">
                    <flux:button type="submit" class="!bg-indigo-700 hover:!bg-indigo-500 !text-white">
                        {{ $editingId ? __('Update Account') : __('Create Account') }}
                    </flux:button>
                    <flux:button wire:click="cancel" variant="ghost" type="button">
                        {{ __('Cancel') }}
                    </flux:button>
                </div>
            </form>
        @endif
    </x-settings.layout>
</section>
