<?php

namespace App\Http\Controllers;

use App\Models\Shop;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\View\View;

class SellerController extends Controller
{
    private function getUsCaRegions(): array
    {
        return [
            'US' => [
                'AL' => 'Alabama', 'AK' => 'Alaska', 'AZ' => 'Arizona', 'AR' => 'Arkansas', 'CA' => 'California', 'CO' => 'Colorado', 'CT' => 'Connecticut', 'DE' => 'Delaware', 'FL' => 'Florida', 'GA' => 'Georgia', 'HI' => 'Hawaii', 'ID' => 'Idaho', 'IL' => 'Illinois', 'IN' => 'Indiana', 'IA' => 'Iowa', 'KS' => 'Kansas', 'KY' => 'Kentucky', 'LA' => 'Louisiana', 'ME' => 'Maine', 'MD' => 'Maryland', 'MA' => 'Massachusetts', 'MI' => 'Michigan', 'MN' => 'Minnesota', 'MS' => 'Mississippi', 'MO' => 'Missouri', 'MT' => 'Montana', 'NE' => 'Nebraska', 'NV' => 'Nevada', 'NH' => 'New Hampshire', 'NJ' => 'New Jersey', 'NM' => 'New Mexico', 'NY' => 'New York', 'NC' => 'North Carolina', 'ND' => 'North Dakota', 'OH' => 'Ohio', 'OK' => 'Oklahoma', 'OR' => 'Oregon', 'PA' => 'Pennsylvania', 'RI' => 'Rhode Island', 'SC' => 'South Carolina', 'SD' => 'South Dakota', 'TN' => 'Tennessee', 'TX' => 'Texas', 'UT' => 'Utah', 'VT' => 'Vermont', 'VA' => 'Virginia', 'WA' => 'Washington', 'WV' => 'West Virginia', 'WI' => 'Wisconsin', 'WY' => 'Wyoming',
            ],
            'CA' => [
                'AB' => 'Alberta', 'BC' => 'British Columbia', 'MB' => 'Manitoba', 'NB' => 'New Brunswick', 'NL' => 'Newfoundland and Labrador', 'NS' => 'Nova Scotia', 'NT' => 'Northwest Territories', 'NU' => 'Nunavut', 'ON' => 'Ontario', 'PE' => 'Prince Edward Island', 'QC' => 'Quebec', 'SK' => 'Saskatchewan', 'YT' => 'Yukon',
            ],
        ];
    }
    
    private function getCombinedRegions(): array
    {
        $regions = $this->getUsCaRegions();
        return array_merge($regions['US'], $regions['CA']);
    }

    public function showShopRegistrationForm(): View|\Illuminate\Http\RedirectResponse
    {
        $shop = Auth::user()->shop;

        if ($shop) {
            return redirect()->route('seller.shop.edit');
        }
        
        return view('seller.shop-register-form', [
            'regions' => $this->getCombinedRegions(), 
            'shop' => null
        ]);
    }
    
    public function editShop(): View
    {
        $shop = Auth::user()->shop;
        
        if (!$shop) {
             return redirect()->route('seller.shop.register');
        }

        return view('seller.shop-register-form', [
            'regions' => $this->getCombinedRegions(), 
            'shop' => $shop
        ]);
    }

    private function geocodeAddress(Request $request): array
    {
        $fullAddress = sprintf(
            '%s, %s, %s %s',
            $request->address_line_1,
            $request->city,
            $request->state,
            $request->zip_code
        );

        $response = Http::get('https://maps.googleapis.com/maps/api/geocode/json', [
            'address' => $fullAddress,
            'key' => env('GOOGLE_MAPS_API_KEY'),
        ]);

        $lat = null;
        $lng = null;

        if ($response->successful() && $response->json('status') === 'OK') {
            $location = $response->json('results.0.geometry.location');
            $lat = $location['lat'] ?? null;
            $lng = $location['lng'] ?? null;
        }

        return ['latitude' => $lat, 'longitude' => $lng];
    }

    public function storeShop(Request $request)
    {
        $user = Auth::user();
        
        $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:shops,name'],
            'tagline' => ['nullable', 'string', 'max:255'],
            'contact_phone' => ['required', 'string', 'max:20'],
            'address_line_1' => ['required', 'string', 'max:255'],
            'city' => ['required', 'string', 'max:100'],
            'state' => ['required', 'string', 'max:5'],
            'zip_code' => ['required', 'string', 'max:10'],
            'opening_time' => ['required', 'date_format:H:i'],
            'closing_time' => ['required', 'date_format:H:i', 'after:opening_time'],
            'logo' => ['nullable', 'image', 'mimes:jpg,jpeg,png', 'max:2048'],
        ]);

        $coordinates = $this->geocodeAddress($request);
        
        $logoPath = null;
        if ($request->hasFile('logo')) {
            $logoPath = $request->file('logo')->store('shops/logos', 'public');
        }
        
        Shop::create([
            'user_id' => $user->id,
            'name' => $request->name,
            'slug' => Str::slug($request->name, '-'),
            'tagline' => $request->tagline,
            'contact_phone' => $request->contact_phone,
            'address_line_1' => $request->address_line_1,
            'city' => $request->city,
            'state' => $request->state,
            'zip_code' => $request->zip_code,
            'latitude' => $coordinates['latitude'],
            'longitude' => $coordinates['longitude'],
            'opening_time' => $request->opening_time,
            'closing_time' => $request->closing_time,
            'logo_path' => $logoPath,
            'status' => 'approved',
        ]);

        return redirect()->route('dashboard')
            ->with('success', 'Shop successfully registered and approved!');
    }
    
    public function updateShop(Request $request)
    {
        $shop = Auth::user()->shop;

        if (!$shop) {
            return redirect()->route('seller.shop.register')
                ->with('error', 'Shop not found. Please register first.');
        }

        $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:shops,name,' . $shop->id],
            'tagline' => ['nullable', 'string', 'max:255'],
            'contact_phone' => ['required', 'string', 'max:20'],
            'address_line_1' => ['required', 'string', 'max:255'],
            'city' => ['required', 'string', 'max:100'],
            'state' => ['required', 'string', 'max:5'],
            'zip_code' => ['required', 'string', 'max:10'],
            'opening_time' => ['required', 'date_format:H:i'],
            'closing_time' => ['required', 'date_format:H:i', 'after:opening_time'],
            'logo' => ['nullable', 'image', 'mimes:jpg,jpeg,png', 'max:2048'],
        ]);

        $coordinates = $this->geocodeAddress($request);

        $data = $request->except(['_token', '_method', 'logo']);
        $data['slug'] = Str::slug($request->name, '-');
        $data['latitude'] = $coordinates['latitude'];
        $data['longitude'] = $coordinates['longitude'];

        if ($request->hasFile('logo')) {
            // Optional: delete old logo here if needed
            $data['logo_path'] = $request->file('logo')->store('shops/logos', 'public');
        }
        
        $shop->update($data);

        return redirect()->route('dashboard')
            ->with('success', 'Shop details successfully updated!');
    }
}
