<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use App\Models\ContactList;
use App\Models\Tag;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ContactImportController extends Controller
{
    public function create()
    {
        return Inertia::render('Audience/ContactsImport', [
            'allLists' => ContactList::orderBy('title')->get(['id', 'title', 'color']),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'rows'               => 'required|array|min:1|max:10000',
            'rows.*'             => 'array',
            'mapping'            => 'required|array',
            'list_ids'           => 'nullable|array',
            'list_ids.*'         => 'exists:lists,id',
            'tag_ids'            => 'nullable|array',
            'tag_ids.*'          => 'exists:tags,id',
            'duplicate_handling' => 'required|in:skip,update',
        ]);

        $rows     = $request->input('rows');
        $mapping  = $request->input('mapping');  // { colIndex => fieldName }
        $listIds  = $request->input('list_ids', []);
        $tagIds   = $request->input('tag_ids', []);
        $dupMode  = $request->input('duplicate_handling', 'skip');

        $results = [
            'imported' => 0,
            'updated'  => 0,
            'skipped'  => 0,
            'errors'   => [],
        ];

        foreach ($rows as $rowIdx => $row) {
            $data = [];

            foreach ($mapping as $colIdx => $field) {
                if (in_array($field, ['__skip__', '', null], true)) continue;
                $data[$field] = isset($row[$colIdx]) ? trim((string) $row[$colIdx]) : null;
            }

            // Validate email
            $email = $data['email'] ?? null;
            if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $results['errors'][] = [
                    'row'    => $rowIdx + 2,
                    'email'  => $email ?? '(blank)',
                    'reason' => 'Invalid or missing email',
                ];
                $results['skipped']++;
                continue;
            }

            // Sanitise date_of_birth
            if (!empty($data['date_of_birth'])) {
                $parsed = strtotime($data['date_of_birth']);
                $data['date_of_birth'] = $parsed ? date('Y-m-d', $parsed) : null;
            }

            $existing = Contact::where('email', $email)->first();

            if ($existing) {
                if ($dupMode === 'update') {
                    $fill = array_filter($data, fn($v) => $v !== null && $v !== '');
                    unset($fill['email']); // don't overwrite email
                    $existing->update($fill);
                    if ($listIds) {
                        $existingListIds = $existing->lists()->pluck('lists.id')->toArray();
                        $existing->lists()->syncWithoutDetaching($listIds);
                        $newListIds = array_diff($listIds, $existingListIds);
                        foreach ($newListIds as $listId) {
                            $listTitle = \App\Models\ContactList::find($listId)?->title ?? "#{$listId}";
                            $existing->logActivity('list_added', "Added to list: {$listTitle}");
                        }
                    }
                    if ($tagIds) {
                        $existingTagIds  = $existing->tags()->pluck('tags.id')->toArray();
                        $existing->tags()->syncWithoutDetaching($tagIds);
                        $newTagIds = array_diff($tagIds, $existingTagIds);
                        foreach ($newTagIds as $tagId) {
                            $tagTitle = \App\Models\Tag::find($tagId)?->title ?? "#{$tagId}";
                            $existing->logActivity('tag_added', "Tag added: {$tagTitle}");
                        }
                    }
                    $results['updated']++;
                } else {
                    $results['skipped']++;
                }
            } else {
                $data['status']       = $data['status']       ?? 'subscribed';
                $data['contact_type'] = $data['contact_type'] ?? 'lead';

                $contact = Contact::create($data);
                if ($listIds) {
                    $contact->lists()->sync($listIds);
                    foreach ($listIds as $listId) {
                        $listTitle = \App\Models\ContactList::find($listId)?->title ?? "#{$listId}";
                        $contact->logActivity('list_added', "Added to list: {$listTitle}");
                    }
                }
                if ($tagIds) {
                    $contact->tags()->sync($tagIds);
                    foreach ($tagIds as $tagId) {
                        $tagTitle = \App\Models\Tag::find($tagId)?->title ?? "#{$tagId}";
                        $contact->logActivity('tag_added', "Tag added: {$tagTitle}");
                    }
                }
                $contact->logActivity('imported', 'Contact imported via CSV');
                $results['imported']++;
            }
        }

        // Create a notification
        $message = "CSV import finished. Imported: {$results['imported']}, Updated: {$results['updated']}, Skipped/Failed: {$results['skipped']}.";
        $type = count($results['errors']) > 0 ? 'warning' : 'success';
        \App\Models\Notification::notify(
            auth()->id(),
            $type,
            'Contact Import Complete',
            $message,
            '/contacts'
        );

        return response()->json([
            'success' => true,
            'results' => $results,
            'total'   => count($rows),
        ]);
    }
}
