<?php

namespace App\Components\WillsCase;

use App\Models\WillsCase\WillsCase;
use App\Services\WillsCaseService;
use Livewire\Attributes\Lazy;
use Livewire\Component;

#[Lazy]
class Edit extends Component {
    public WillsCase $willsCase;

    // Case fields
    public string $case_number        = '';
    public string $opened_at          = '';
    public string $closed_at          = '';
    public string $ifa_referred_date  = '';
    public string $national_insurance = '';
    public bool   $ifa_referred       = false;
    public bool   $is_open            = true;
    public string $fee_structure      = '';
    public string $occupation         = '';

    // New fields
    public string $rep              = '';
    public string $case_owner       = '';
    public array  $products         = [];
    public string $drafting_contact = '';
    public string $our_fee          = '';
    public string $awt_invoice_issued_at = '';
    public string $our_fee_status   = '';
    public string $external_draft_fee = '';
    public string $welcome_letter_sent_at = '';
    public string $docs_outstanding_from_reps = '';
    public string $introduction_call_at = '';
    public string $intro_call_by    = '';
    public string $trust_docs_instructed_at = '';
    public string $in_house_instructed_at = '';
    public string $drafts_received_at = '';
    public string $drafts_issued_to_client_at = '';
    public string $master_copies_signed_at = '';
    public string $master_copies_received_at = '';
    public string $date_on_document_signed = '';
    public ?bool  $documents_requiring_registration = null;
    public array  $documents_to_register_aiker = [];
    public array  $documents_to_register_external = [];
    public array  $registration_completed_aiker = [];
    public array  $registration_completed_external = [];
    public string $client_letters_from_hmrc_at = '';
    public string $annual_minutes_task_set_at = '';

    // Client fields
    public string $client_title          = '';
    public string $client_first_name     = '';
    public string $client_middle_name    = '';
    public string $client_last_name      = '';
    public string $client_preferred_name = '';
    public string $client_dob            = '';
    public string $client_email          = '';
    public string $client_phone          = '';
    public string $client_landline       = '';

    public function mount(WillsCase $willsCase): void {
        $this->willsCase = $willsCase;

        $this->case_number        = $willsCase->case_number ?? '';
        $this->opened_at          = $willsCase->opened_at?->format('Y-m-d') ?? '';
        $this->closed_at          = $willsCase->closed_at?->format('Y-m-d') ?? '';
        $this->ifa_referred_date  = $willsCase->ifa_referred_date?->format('Y-m-d') ?? '';
        $this->national_insurance = $willsCase->national_insurance ?? '';
        $this->ifa_referred       = (bool) $willsCase->ifa_referred;
        $this->is_open            = (bool) $willsCase->is_open;
        $this->fee_structure      = $willsCase->fee_structure ?? '';
        $this->occupation         = $willsCase->occupation ?? '';

        $this->rep                = $willsCase->rep ?? '';
        $this->case_owner         = $willsCase->case_owner ?? '';
        $this->products           = $willsCase->products ?? [];
        $this->drafting_contact   = $willsCase->drafting_contact ?? '';
        $this->our_fee            = $willsCase->our_fee ?? '';
        $this->awt_invoice_issued_at = $willsCase->awt_invoice_issued_at?->format('Y-m-d') ?? '';
        $this->our_fee_status     = $willsCase->our_fee_status ?? '';
        $this->external_draft_fee = $willsCase->external_draft_fee ?? '';
        $this->welcome_letter_sent_at = $willsCase->welcome_letter_sent_at?->format('Y-m-d') ?? '';
        $this->docs_outstanding_from_reps = $willsCase->docs_outstanding_from_reps ?? '';
        $this->introduction_call_at = $willsCase->introduction_call_at?->format('Y-m-d') ?? '';
        $this->intro_call_by      = $willsCase->intro_call_by ?? '';
        $this->trust_docs_instructed_at = $willsCase->trust_docs_instructed_at?->format('Y-m-d') ?? '';
        $this->in_house_instructed_at = $willsCase->in_house_instructed_at?->format('Y-m-d') ?? '';
        $this->drafts_received_at = $willsCase->drafts_received_at?->format('Y-m-d') ?? '';
        $this->drafts_issued_to_client_at = $willsCase->drafts_issued_to_client_at?->format('Y-m-d') ?? '';
        $this->master_copies_signed_at = $willsCase->master_copies_signed_at?->format('Y-m-d') ?? '';
        $this->master_copies_received_at = $willsCase->master_copies_received_at?->format('Y-m-d') ?? '';
        $this->date_on_document_signed = $willsCase->date_on_document_signed?->format('Y-m-d') ?? '';
        $this->documents_requiring_registration = $willsCase->documents_requiring_registration;
        $this->documents_to_register_aiker    = $willsCase->documents_to_register_aiker ?? [];
        $this->documents_to_register_external = $willsCase->documents_to_register_external ?? [];
        $this->client_letters_from_hmrc_at = $willsCase->client_letters_from_hmrc_at?->format('Y-m-d') ?? '';
        $this->annual_minutes_task_set_at  = $willsCase->annual_minutes_task_set_at?->format('Y-m-d') ?? '';

        // Expand stored JSON dates to indexed array for form binding
        $storedAiker    = $willsCase->registration_completed_aiker ?? [];
        $storedExternal = $willsCase->registration_completed_external ?? [];
        foreach (\App\Models\WillsCase\WillsCase::REGISTRATION_DOC_OPTIONS as $idx => $doc) {
            $this->registration_completed_aiker[$idx]    = $storedAiker[$doc] ?? '';
            $this->registration_completed_external[$idx] = $storedExternal[$doc] ?? '';
        }

        $client = $willsCase->client;
        $this->client_title          = $client->title ?? '';
        $this->client_first_name     = $client->name_first ?? '';
        $this->client_middle_name    = $client->name_middle ?? '';
        $this->client_last_name      = $client->name_last ?? '';
        $this->client_preferred_name = $client->name_preferred ?? '';
        $this->client_dob            = $client->date_of_birth?->format('Y-m-d') ?? '';
        $this->client_email          = (string) $client->email_address;
        $this->client_phone          = (string) $client->phone_number;
        $this->client_landline       = (string) $client->landline;
    }

    protected function rules(): array {
        return [
            'case_number'        => 'nullable|string|max:255',
            'opened_at'          => 'nullable|date',
            'closed_at'          => 'nullable|date',
            'ifa_referred_date'  => 'nullable|date',
            'national_insurance' => 'nullable|string|max:20',
            'ifa_referred'       => 'boolean',
            'is_open'            => 'boolean',
            'fee_structure'      => 'nullable|string|max:255',
            'occupation'         => 'nullable|string|max:255',

            'rep'                            => 'nullable|string|max:255',
            'case_owner'                     => 'nullable|string|max:50',
            'products'                       => 'nullable|array',
            'products.*'                     => 'string',
            'drafting_contact'               => 'nullable|string|max:255',
            'our_fee'                        => 'nullable|string|max:255',
            'awt_invoice_issued_at'          => 'nullable|date',
            'our_fee_status'                 => 'nullable|string|max:50',
            'external_draft_fee'             => 'nullable|string|max:255',
            'welcome_letter_sent_at'         => 'nullable|date',
            'docs_outstanding_from_reps'     => 'nullable|string',
            'introduction_call_at'           => 'nullable|date',
            'intro_call_by'                  => 'nullable|string|max:50',
            'trust_docs_instructed_at'       => 'nullable|date',
            'in_house_instructed_at'         => 'nullable|date',
            'drafts_received_at'             => 'nullable|date',
            'drafts_issued_to_client_at'     => 'nullable|date',
            'master_copies_signed_at'        => 'nullable|date',
            'master_copies_received_at'      => 'nullable|date',
            'date_on_document_signed'        => 'nullable|date',
            'documents_requiring_registration' => 'nullable|boolean',
            'documents_to_register_aiker'    => 'nullable|array',
            'documents_to_register_aiker.*'  => 'string',
            'documents_to_register_external'   => 'nullable|array',
            'documents_to_register_external.*' => 'string',
            'registration_completed_aiker'   => 'nullable|array',
            'registration_completed_external' => 'nullable|array',
            'client_letters_from_hmrc_at'    => 'nullable|date',
            'annual_minutes_task_set_at'     => 'nullable|date',

            'client_title'          => ['nullable', 'string', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'client_first_name'     => ['required', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'client_middle_name'    => ['nullable', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'client_last_name'      => ['required', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'client_preferred_name' => ['nullable', 'string', 'min:2', 'max:50', 'regex:/^[a-zA-Z\'\-\s]+$/'],
            'client_dob'            => ['nullable', 'date', 'before:-18 years', 'after:-120 years'],
            'client_email'          => ['nullable', 'email:rfc'],
            'client_phone'          => ['nullable'],
            'client_landline'       => ['nullable'],
        ];
    }

    public function save(WillsCaseService $service): void {
        $this->validate();

        $service->update($this->willsCase, [
            'case_number'        => $this->case_number ?: null,
            'opened_at'          => $this->opened_at ?: null,
            'closed_at'          => $this->closed_at ?: null,
            'ifa_referred_date'  => $this->ifa_referred_date ?: null,
            'national_insurance' => $this->national_insurance ?: null,
            'ifa_referred'       => $this->ifa_referred,
            'is_open'            => $this->is_open,
            'is_closed'          => !$this->is_open,
            'fee_structure'      => $this->fee_structure ?: null,
            'occupation'         => $this->occupation ?: null,
            'rep'                            => $this->rep ?: null,
            'case_owner'                     => $this->case_owner ?: null,
            'products'                       => $this->products ?: null,
            'drafting_contact'               => $this->drafting_contact ?: null,
            'our_fee'                        => $this->our_fee ?: null,
            'awt_invoice_issued_at'          => $this->awt_invoice_issued_at ?: null,
            'our_fee_status'                 => $this->our_fee_status ?: null,
            'external_draft_fee'             => $this->external_draft_fee ?: null,
            'welcome_letter_sent_at'         => $this->welcome_letter_sent_at ?: null,
            'docs_outstanding_from_reps'     => $this->docs_outstanding_from_reps ?: null,
            'introduction_call_at'           => $this->introduction_call_at ?: null,
            'intro_call_by'                  => $this->intro_call_by ?: null,
            'trust_docs_instructed_at'       => $this->trust_docs_instructed_at ?: null,
            'in_house_instructed_at'         => $this->in_house_instructed_at ?: null,
            'drafts_received_at'             => $this->drafts_received_at ?: null,
            'drafts_issued_to_client_at'     => $this->drafts_issued_to_client_at ?: null,
            'master_copies_signed_at'        => $this->master_copies_signed_at ?: null,
            'master_copies_received_at'      => $this->master_copies_received_at ?: null,
            'date_on_document_signed'        => $this->date_on_document_signed ?: null,
            'documents_requiring_registration' => $this->documents_requiring_registration,
            'documents_to_register_aiker'    => $this->documents_to_register_aiker ?: null,
            'documents_to_register_external' => $this->documents_to_register_external ?: null,
            'registration_completed_aiker'   => $this->buildRegistrationDates($this->registration_completed_aiker, $this->documents_to_register_aiker),
            'registration_completed_external' => $this->buildRegistrationDates($this->registration_completed_external, $this->documents_to_register_external),
            'client_letters_from_hmrc_at'    => $this->client_letters_from_hmrc_at ?: null,
            'annual_minutes_task_set_at'     => $this->annual_minutes_task_set_at ?: null,
        ]);

        $this->willsCase->client->update([
            'title'          => $this->standardiseName($this->client_title),
            'name_first'     => $this->standardiseName($this->client_first_name),
            'name_middle'    => $this->standardiseName($this->client_middle_name),
            'name_last'      => $this->standardiseName($this->client_last_name),
            'name_preferred' => $this->standardiseName($this->client_preferred_name),
            'date_of_birth'  => $this->client_dob ?: null,
            'email_address'  => $this->client_email ? strtolower(trim($this->client_email)) : null,
            'phone_number'   => $this->client_phone ? str_replace(' ', '', $this->client_phone) : null,
            'landline'       => $this->client_landline ? str_replace(' ', '', $this->client_landline) : null,
        ]);

        $this->dispatch('toast', title: 'Case updated', type: 'success');

        $this->redirectRoute('wills-cases.view', $this->willsCase);
    }

    protected function buildRegistrationDates(array $datesIndexed, array $selectedDocs): ?array {
        $result = [];
        foreach (\App\Models\WillsCase\WillsCase::REGISTRATION_DOC_OPTIONS as $idx => $doc) {
            if (in_array($doc, $selectedDocs, true) && !empty($datesIndexed[$idx])) {
                $result[$doc] = $datesIndexed[$idx];
            }
        }
        return $result ?: null;
    }

    protected function standardiseName(?string $value): ?string {
        if (!$value) {
            return null;
        }
        $value = trim($value);
        $value = preg_replace('/\s+/', ' ', $value);
        return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8');
    }

    public function render() {
        return view('components.wills-case.edit');
    }

    public function placeholder() {
        return '<div class="p-4"><div class="placeholder-glow"><span class="placeholder col-6 placeholder-lg"></span></div></div>';
    }
}
