<?php

namespace App\Livewire\Invoices;

use App\Domain\Financial\Enums\InvoiceStatus;
use App\Domain\Financial\Enums\PaymentMethod;
use App\Domain\Financial\Models\Invoice;
use App\Domain\Financial\Services\InvoiceService;
use App\Domain\Financial\Services\PaymentService;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفاصيل الفاتورة')]
class InvoiceShow extends Component
{
    public Invoice $invoice;

    // Payment form
    public float $paymentAmount = 0;
    public string $paymentMethod = 'cash';
    public string $paymentDate = '';
    public string $paymentNotes = '';

    public function mount(Invoice $invoice): void
    {
        $this->authorize('invoices.view');
        $this->invoice = $invoice->load(['items', 'payments', 'billable', 'creator']);
        $this->paymentDate = now()->format('Y-m-d');
        $this->paymentAmount = $invoice->due_amount / 100;
    }

    public function recordPayment(PaymentService $service): void
    {
        $this->validate([
            'paymentAmount' => 'required|numeric|min:0.01',
            'paymentMethod' => 'required|in:cash,card,bank_transfer,wallet,online,cheque,other',
            'paymentDate' => 'required|date',
        ], [
            'paymentAmount.required' => 'المبلغ مطلوب',
            'paymentAmount.min' => 'المبلغ يجب أن يكون أكبر من صفر',
            'paymentMethod.required' => 'طريقة الدفع مطلوبة',
            'paymentDate.required' => 'تاريخ الدفع مطلوب',
        ]);

        $amountInPiasters = (int) round($this->paymentAmount * 100);

        if ($amountInPiasters > $this->invoice->due_amount) {
            session()->flash('error', __('المبلغ أكبر من المستحق'));
            return;
        }

        try {
            $service->recordPayment([
                'academy_id' => $this->invoice->academy_id,
                'branch_id' => auth()->user()->branch_id ?? $this->invoice->branch_id ?? null,
                'invoice_id' => $this->invoice->id,
                'reference' => 'PAY-' . now()->format('YmdHis') . '-' . rand(100, 999),
                'direction' => 'inbound',
                'method' => $this->paymentMethod,
                'payer_type' => $this->invoice->billable_type,
                'payer_id' => $this->invoice->billable_id,
                'amount' => $amountInPiasters,
                'currency' => 'EGP',
                'payment_date' => $this->paymentDate,
                'notes' => $this->paymentNotes ?: null,
                'received_by' => auth()->id(),
                'created_by' => auth()->id(),
            ], auth()->user());

            $this->invoice->refresh()->load(['items', 'payments', 'billable', 'creator']);
            $this->paymentAmount = $this->invoice->due_amount / 100;
            $this->paymentNotes = '';
            $this->dispatch('payment-recorded');
            session()->flash('success', __('تم تسجيل الدفعة بنجاح'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        } catch (\Exception $e) {
            session()->flash('error', __('حدث خطأ أثناء تسجيل الدفعة'));
        }
    }

    public function cancelInvoice(InvoiceService $service): void
    {
        try {
            $service->cancel($this->invoice, auth()->user());
            $this->invoice->refresh();
            session()->flash('success', __('تم إلغاء الفاتورة'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        } catch (\Exception $e) {
            session()->flash('error', __('لا يمكن إلغاء هذه الفاتورة'));
        }
    }

    public function getCanCancelProperty(): bool
    {
        return in_array($this->invoice->status, [InvoiceStatus::Draft, InvoiceStatus::Sent])
            && $this->invoice->paid_amount === 0;
    }

    public function getCanRecordPaymentProperty(): bool
    {
        return $this->invoice->due_amount > 0
            && !in_array($this->invoice->status, [InvoiceStatus::Cancelled, InvoiceStatus::Refunded]);
    }

    public function render()
    {
        return view('livewire.invoices.invoice-show', [
            'paymentMethods' => collect(PaymentMethod::cases())->mapWithKeys(
                fn (PaymentMethod $m) => [$m->value => $m->label()]
            )->toArray(),
        ]);
    }
}
