<?php

namespace App\Components\PensionCase;

use App\Models\Client\Client;
use App\Models\LeadSource\LeadSource;
use App\Services\HistoryService;
use App\Services\PensionCaseService;
use Livewire\Attributes\Lazy;
use Livewire\Component;

#[Lazy]
class Create extends Component {
    public ?Client $client = null;

    // New client fields (only used when no client is pre-set)
    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_phone = '';
    public string $client_email = '';
    public ?int $client_lead_source_id = null;

    // Per-case lead source (distinct from the client's)
    public ?int $case_lead_source_id = null;

    // Claim type (required at creation)
    public string $claim_type = '';

    // Case identity
    public string $sf_case_id = '';
    public string $case_number = '';
    public string $case_owner = '';
    public string $claims_writer = '';
    public string $file_investigator = '';

    // Claim details
    public string $claim_subject = '';
    public string $claim_basis = '';
    public string $priority = '';
    public string $underlying_investment = '';
    public string $investment_library = '';

    // Statuses
    public string $settlement_status = '';
    public string $bank_claim_status = '';
    public string $fos_claim_status = '';
    public string $fscs_claim_status = '';

    // Client flags
    public bool $is_open = true;
    public bool $vulnerable_client_flag = false;
    public string $vulnerable_client_details = '';
    public bool $special_contact_requirements_flag = false;
    public string $special_contact_requirements_details = '';
    public bool $sms_opt_out = false;
    public bool $do_not_contact = false;
    public bool $ifa_referred = false;
    public bool $fee_capping_flag = false;

    // Client identifiers
    public string $national_insurance = '';
    public string $cmc_client_reference = '';
    public string $fee_structure = '';

    public function mount(?Client $client = null): void {
        $this->client = $client;
    }

    protected function rules(): array {
        $clientRules = $this->client ? [] : [
            '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_phone'           => ['nullable'],
            'client_email'           => ['nullable', 'email:rfc'],
            'client_lead_source_id'  => ['nullable', 'exists:lead_sources,id'],
        ];

        return array_merge($clientRules, [
            'claim_type'           => 'required|in:bank,fscs,fos',
            'case_lead_source_id'  => ['nullable', 'exists:lead_sources,id'],
            'case_number'         => 'nullable|string|max:255',
            'sf_case_id'          => 'nullable|string|max:255',
            'case_owner'          => 'nullable|string|max:255',
            'claims_writer'       => 'nullable|string|max:255',
            'file_investigator'   => 'nullable|string|max:255',
            'claim_subject'       => 'nullable|string|max:255',
            'claim_basis'         => 'nullable|string|max:255',
            'priority'            => 'nullable|string|max:255',
            'settlement_status'   => 'nullable|string|max:255',
            'bank_claim_status'   => 'nullable|string|max:255',
            'fos_claim_status'    => 'nullable|string|max:255',
            'fscs_claim_status'   => 'nullable|string|max:255',
            'national_insurance'  => 'nullable|string|max:20',
            'cmc_client_reference' => 'nullable|string|max:255',
        ]);
    }

    protected function messages(): array {
        return [
            'client_first_name.regex'     => 'First name contains invalid characters.',
            'client_middle_name.regex'    => 'Middle name contains invalid characters.',
            'client_last_name.regex'      => 'Last name contains invalid characters.',
            'client_preferred_name.regex' => 'Preferred name contains invalid characters.',
        ];
    }

    public function save(PensionCaseService $service, HistoryService $history): void {
        $this->validate();

        if (!$this->client) {
            $this->client = Client::create([
                '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,
                'phone_number'   => $this->client_phone ? str_replace(' ', '', $this->client_phone) : null,
                'email_address'  => $this->client_email ? strtolower(trim($this->client_email)) : null,
                'lead_source_id' => $this->client_lead_source_id,
            ]);

            $history->add($this->client, 'Client created via CPF case creation.');
        }

        $data = [
            'claim_type'                         => $this->claim_type,
            'sf_case_id'                         => $this->sf_case_id ?: null,
            'case_number'                        => $this->case_number ?: null,
            'case_owner'                         => $this->case_owner ?: null,
            'claims_writer'                      => $this->claims_writer ?: null,
            'file_investigator'                  => $this->file_investigator ?: null,
            'claim_subject'                      => $this->claim_subject ?: null,
            'claim_basis'                        => $this->claim_basis ?: null,
            'priority'                           => $this->priority ?: null,
            'underlying_investment'              => $this->underlying_investment ?: null,
            'investment_library'                 => $this->investment_library ?: null,
            'settlement_status'                  => $this->settlement_status ?: null,
            'bank_claim_status'                  => $this->bank_claim_status ?: null,
            'fos_claim_status'                   => $this->fos_claim_status ?: null,
            'fscs_claim_status'                  => $this->fscs_claim_status ?: null,
            'is_open'                            => $this->is_open,
            'is_closed'                          => !$this->is_open,
            'vulnerable_client_flag'             => $this->vulnerable_client_flag,
            'vulnerable_client_details'          => $this->vulnerable_client_details ?: null,
            'special_contact_requirements_flag'  => $this->special_contact_requirements_flag,
            'special_contact_requirements_details' => $this->special_contact_requirements_details ?: null,
            'sms_opt_out'                        => $this->sms_opt_out,
            'do_not_contact'                     => $this->do_not_contact,
            'ifa_referred'                       => $this->ifa_referred,
            'fee_capping_flag'                   => $this->fee_capping_flag,
            'national_insurance'                 => $this->national_insurance ?: null,
            'cmc_client_reference'               => $this->cmc_client_reference ?: null,
            'fee_structure'                      => $this->fee_structure ?: null,
            'lead_source_id'                     => $this->case_lead_source_id ?: null,
            'opened_at'                          => now(),
        ];

        $case = $service->create($this->client, $data);

        $this->dispatch('toast', title: 'Pension case created', type: 'success');

        $this->redirectRoute('pension-cases.view', $case);
    }

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

    public function render() {
        return view('components.pension-case.create', [
            'leadSources' => LeadSource::pluck('display_name', 'id')->toArray(),
        ]);
    }

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