<?php

namespace App\Filament\Imports;

use App\Models\ImportTransit;
use Filament\Actions\Imports\ImportColumn;
use Filament\Actions\Imports\Importer;
use Filament\Actions\Imports\Models\Import;
use Filament\Actions\Imports\Exceptions\RowImportFailedException;
use Carbon\Carbon;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Log;

class ImportTransitImporter extends Importer
{
    protected static ?string $model = ImportTransit::class;

    public static function getColumns(): array
    {
        return [
            ImportColumn::make('cri_rfq_number')
                ->requiredMapping()
                ->exampleHeader('CRI RFQ Number')
                ->example('RFQ-IMP-C.R.I-2025-A')
                ->label('CRI RFQ Number')
                ->rules(['required']),
            ImportColumn::make('mail_received_date')
                ->requiredMapping()
                ->exampleHeader('Mail Received Date')
                ->example('2024-01-01')
                ->label('Mail Received Date'),
            ImportColumn::make('pricol_ref_number')
                ->exampleHeader('Pricol Ref Number')
                ->example('ENQ-1649')
                ->label('Pricol Ref Number'),
            ImportColumn::make('requester')
                ->exampleHeader('Requester')
                ->example('Mr.Sathish.K')
                ->label('Requester'),
            ImportColumn::make('shipper')
                ->exampleHeader('Shipper')
                ->example('Zhejiang shenneng technology co.,ltd')
                ->label('Shipper'),
            ImportColumn::make('shipper_location')
                ->exampleHeader('Shipper Location')
                ->example('China')
                ->label('Shipper Location'),
            ImportColumn::make('shipper_invoice')
                ->exampleHeader('Shipper Invoice')
                ->example('SNINDIA250618')
                ->label('Shipper Invoice'),
            ImportColumn::make('shipper_invoice_date')
                ->exampleHeader('Shipper Invoice Date')
                ->example('2024-01-02')
                ->label('Shipper Invoice Date'),
            ImportColumn::make('inv_value')
                ->exampleHeader('Inv Value')
                ->example('10000')
                ->label('Inv Value'),
            ImportColumn::make('freight_charge')
                ->exampleHeader('Freight Charge')
                ->example('500')
                ->label('Freight Charge'),
            ImportColumn::make('customs_agent_name')
                ->exampleHeader('Customs Agent Name')
                ->example('Pricol Logistics')
                ->label('Customs Agent Name'),
            ImportColumn::make('eta_date')
                ->exampleHeader('ETA Date')
                ->example('2024-01-10')
                ->label('ETA Date'),
            ImportColumn::make('status')
                ->exampleHeader('Status')
                ->example('Receipted')
                ->label('Status'),
            ImportColumn::make('insurance_status')
                ->exampleHeader('Insurance Status')
                ->example('Yes')
                ->label('Insurance Status'),
            ImportColumn::make('delivery_location')
                ->exampleHeader('Delivery Location')
                ->example('Arasur Hub')
                ->label('Delivery Location'),
            ImportColumn::make('etd_date')
                ->exampleHeader('ETD Date')
                ->example('2024-01-05')
                ->label('ETD Date'),
            ImportColumn::make('mode')
                ->exampleHeader('Mode')
                ->example('LCL')
                ->label('Mode'),
            ImportColumn::make('inco_terms')
                ->exampleHeader('Inco Terms')
                ->example('FOB')
                ->label('Inco Terms'),
            ImportColumn::make('port_of_loading')
                ->exampleHeader('Port of Loading')
                ->example('NINGBO')
                ->label('Port of Loading'),
            ImportColumn::make('port_of_discharge')
                ->exampleHeader('Port of Discharge')
                ->example('CHENNAI')
                ->label('Port of Discharge'),
            ImportColumn::make('delivery_city')
                ->exampleHeader('Delivery City')
                ->example('COIMBATORE')
                ->label('Delivery City'),
            ImportColumn::make('packages')
                ->exampleHeader('Packages')
                ->example('450')
                ->label('Packages'),
            ImportColumn::make('type_of_package')
                ->exampleHeader('Type of Package')
                ->example('PKG')
                ->label('Type of Package'),
            ImportColumn::make('gross_weight')
                ->exampleHeader('Gross Weight')
                ->example('5000')
                ->label('Gross Weight'),
            ImportColumn::make('volume')
                ->exampleHeader('Volume')
                ->example('50')
                ->label('Volume'),
            ImportColumn::make('bill_number')
                ->exampleHeader('Bill Number')
                ->example('BL12345')
                ->label('Bill Number'),
            ImportColumn::make('bill_received_date')
                ->exampleHeader('Bill Received Date')
                ->example('2024-01-15')
                ->label('Bill Received Date'),
            ImportColumn::make('vessel_number')
                ->exampleHeader('Vessel Number')
                ->example('XIN WEN ZHOU')
                ->label('Vessel Number'),
        ];
    }

    public function resolveRecord(): ?ImportTransit
    {
        $warnMsg = [];
        $criRfqNumber = trim($this->data['cri_rfq_number']) ?? '';
        $mailRecDate = trim($this->data['mail_received_date']) ?? '';
        $pricolRefNumber = trim($this->data['pricol_ref_number']) ?? '';
        $requester = trim($this->data['requester']) ?? '';
        $shipper = trim($this->data['shipper']) ?? '';
        $shipperLocation = trim($this->data['shipper_location']) ?? '';
        $shipperInvoice = trim($this->data['shipper_invoice']) ?? '';
        $shipperInvoiceDt = trim($this->data['shipper_invoice_date']) ?? '';
        $invValue = trim($this->data['inv_value']) ?? '';
        $freightCharge = trim($this->data['freight_charge']) ?? '';
        $customsAgentname = trim($this->data['customs_agent_name']) ?? '';
        $etaDate = trim($this->data['eta_date']) ?? '';
        $status = trim($this->data['status']) ?? '';
        $deliveryLocation = trim($this->data['delivery_location']) ?? '';
        $etdDate = trim($this->data['etd_date']) ?? '';
        $mode = trim($this->data['mode']) ?? '';
        $incoTerms = trim($this->data['inco_terms']) ?? '';
        $portOfLoading = trim($this->data['port_of_loading']) ?? '';
        $portOfDischarge = trim($this->data['port_of_discharge']) ?? '';
        $deliveryCity = trim($this->data['delivery_city']) ?? '';
        $packages = trim($this->data['packages']) ?? '';
        $typeOfPackage = trim($this->data['type_of_package']) ?? '';
        $grossWeight = trim($this->data['gross_weight']) ?? '';
        $volume = trim($this->data['volume']) ?? '';
        $billNo = trim($this->data['bill_number']) ?? '';
        $billReceivedDate = trim($this->data['bill_received_date']) ?? '';
        $vesselNumber = trim($this->data['vessel_number']) ?? '';

        $createdBy = Filament::auth()->user()?->name ?? '';
        $updatedBy = $createdBy;

        if (! empty($warnMsg)) {
            throw new RowImportFailedException(implode(', ', $warnMsg));
        }

        return ImportTransit::updateOrCreate([
            'cri_rfq_number' => $criRfqNumber,
            'shipper_invoice' => $shipperInvoice,
        ],
            [
                'mail_received_date' => $this->formatDate($mailRecDate),
                'shipper_invoice_date' => $this->formatDate($shipperInvoiceDt),
                'eta_date' => $this->formatDate($etaDate),
                'etd_date' => $this->formatDate($etdDate),
                'bill_received_date' => $this->formatDate($billReceivedDate),
                'pricol_ref_number' => $pricolRefNumber,
                'requester' => $requester,
                'shipper' => $shipper,
                'shipper_location' => $shipperLocation,
                'inv_value' => $invValue,
                'freight_charge' => $freightCharge,
                'custom_agent_name' => $customsAgentname,
                'status' => $status,
                'delivery_location' => $deliveryLocation,
                'mode' => $mode,
                'inco_terms' => $incoTerms,
                'port_of_loading' => $portOfLoading,
                'port_of_discharge' => $portOfDischarge,
                'delivery_city' => $deliveryCity,
                'packages' => $packages,
                'type_of_package' => $typeOfPackage,
                'gross_weight' => $grossWeight,
                'volume' => $volume,
                'bill_number' => $billNo,
                'vessel_number' => $vesselNumber,
                // 'created_at' => $createdAt ?? null,
                // 'updated_at' => $updatedAt ?? null,
                'created_by' => $createdBy ?? null,
                'updated_by' => $updatedBy ?? null,
            ]
        );
        // return new ImportTransit();
    }

    private function formatDate($date): ?string
    {
        if (blank($date)) {
            return null;
        }

        if (!preg_match('/\d/', $date)) {
            return null;
        }

        try {
            $date = trim($date);

            // Excel numeric date (e.g. 46000)
            if (is_numeric($date)) {
                return Carbon::instance(
                    \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject((float)$date)
                )->format('Y-m-d');
            }

            // Try common formats explicitly
            $formats = ['d-m-Y', 'd/m/Y', 'Y-m-d', 'm/d/Y', 'd.m.Y'];

            foreach ($formats as $format) {
                try {
                    return Carbon::createFromFormat($format, $date)->format('Y-m-d');
                } catch (\Exception $e) {
                    continue;
                }
            }

            return null;

        } catch (\Exception $e) {
            return null;
        }
    }

    public static function getCompletedNotificationBody(Import $import): string
    {
        $body = 'Your import transit import has completed and ' . number_format($import->successful_rows) . ' ' . str('row')->plural($import->successful_rows) . ' imported.';

        if ($failedRowsCount = $import->getFailedRowsCount()) {
            $body .= ' ' . number_format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to import.';
        }

        return $body;
    }
}
