import { useEffect, useState } from 'react'
import { MapContainer, TileLayer, Circle, useMapEvents, Marker, Popup } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'
import { adminService, ShippingSettings } from '@/services/adminService'
import { useAuth } from '@/context/AuthContext'
import { FaTruck, FaLocationDot, FaStore, FaCircleInfo, FaFloppyDisk } from 'react-icons/fa6'
import { Shell } from '@/layouts/Shell'

import L from 'leaflet'

// Fix Leaflet marker icon issue in React
import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';

let DefaultIcon = L.icon({
    iconUrl: icon,
    shadowUrl: iconShadow,
    iconSize: [25, 41],
    iconAnchor: [12, 41]
});

L.Marker.prototype.options.icon = DefaultIcon;

function RadiusController({ center, setRadius }: { center: [number, number], setRadius: (r: number) => void }) {
    const map = useMapEvents({
        click(e) {
            const distanceMeters = e.latlng.distanceTo(center);
            setRadius(parseFloat((distanceMeters / 1000).toFixed(2)));
        },
    })
    return null
}

export function ShippingSettingsPage() {
    const { user } = useAuth()
    const [settings, setSettings] = useState<ShippingSettings>({
        active: false,
        max_radius_km: 5,
        price_per_km_cents: 0,
        min_fee_cents: 0,
        free_shipping_threshold_cents: 0,
        pickup_active: false,
        pickup_address: '',
        pickup_hours: '',
        latitude: -23.55052, // Default SP
        longitude: -46.633308
    })
    const [loading, setLoading] = useState(true)
    const [saving, setSaving] = useState(false)

    useEffect(() => {
        if (user?.companyId) {
            loadSettings()
        }
    }, [user?.companyId])

    const loadSettings = async () => {
        if (!user?.companyId) return
        setLoading(true)
        try {
            // Fetch company first to get canonical location if needed
            const company = await adminService.getCompany(user.companyId)
            let initialLat = company.latitude || -23.55052
            let initialLng = company.longitude || -46.633308

            const data = await adminService.getShippingSettings(user.companyId)

            // If settings exist and have valid lat/long, use them. Otherwise use company's.
            if (data && (data.latitude !== 0 || data.longitude !== 0)) {
                initialLat = data.latitude
                initialLng = data.longitude
            }

            setSettings({
                ...data,
                // Ensure defaults if null/undefined
                max_radius_km: data?.max_radius_km ?? 5,
                price_per_km_cents: data?.price_per_km_cents ?? 0,
                min_fee_cents: data?.min_fee_cents ?? 0,
                free_shipping_threshold_cents: data?.free_shipping_threshold_cents ?? 0,
                latitude: initialLat,
                longitude: initialLng
            })
        } catch (err) {
            console.error("Error loading settings", err)
        } finally {
            setLoading(false)
        }
    }

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault()
        if (!user?.companyId) return
        setSaving(true)
        try {
            await adminService.upsertShippingSettings(user.companyId, settings)
            alert('Configurações salvas com sucesso!')
        } catch (err) {
            console.error("Error saving settings", err)
            alert('Erro ao salvar configurações.')
        } finally {
            setSaving(false)
        }
    }

    const center: [number, number] = [settings.latitude, settings.longitude]

    if (loading) return (
        <Shell>
            <div className="p-8 text-center text-gray-500">Carregando configurações de frete...</div>
        </Shell>
    )

    return (
        <Shell>
            <div className="max-w-6xl mx-auto space-y-6">
                <div className="flex items-center gap-3 mb-6">
                    <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gray-100">
                        <FaTruck size={24} color="black" />
                    </div>
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900">Configurações de Entrega e Retirada</h1>
                        <p className="text-sm text-gray-500">Defina as opções de frete e retirada da sua loja</p>
                    </div>
                </div>

                <form onSubmit={handleSave} className="grid grid-cols-1 lg:grid-cols-2 gap-6">

                    {/* Delivery Settings */}
                    <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
                        <div className="flex items-center justify-between mb-4">
                            <h2 className="text-lg font-semibold flex items-center gap-2">
                                <FaLocationDot size={18} color="black" />
                                Entrega Própria
                            </h2>
                            <label className="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" className="sr-only peer" checked={settings.active} onChange={e => setSettings({ ...settings, active: e.target.checked })} />
                                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all" style={{ '--tw-ring-color': '#0F4C81' } as React.CSSProperties}></div>
                                <span className="ml-3 text-sm font-medium text-gray-900">{settings.active ? 'Ativado' : 'Desativado'}</span>
                            </label>
                        </div>

                        <div className={`space-y-4 ${!settings.active && 'opacity-50 pointer-events-none'}`}>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Raio de Entrega (km)</label>
                                <input
                                    type="number"
                                    step="0.1"
                                    className="w-full p-2 border rounded"
                                    value={settings.max_radius_km}
                                    onChange={e => setSettings({ ...settings, max_radius_km: parseFloat(e.target.value) })}
                                />
                                <p className="text-xs text-gray-500 mt-1">Clique no mapa para definir o raio visualmente.</p>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Preço por Km (Centavos)</label>
                                    <div className="relative">
                                        <span className="absolute left-3 top-2 text-gray-500">R$</span>
                                        <input
                                            type="number"
                                            className="w-full pl-8 p-2 border rounded"
                                            value={(settings.price_per_km_cents / 100).toFixed(2)}
                                            onChange={e => setSettings({ ...settings, price_per_km_cents: Math.round(parseFloat(e.target.value) * 100) })}
                                        />
                                    </div>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">Taxa Mínima</label>
                                    <div className="relative">
                                        <span className="absolute left-3 top-2 text-gray-500">R$</span>
                                        <input
                                            type="number"
                                            className="w-full pl-8 p-2 border rounded"
                                            value={(settings.min_fee_cents / 100).toFixed(2)}
                                            onChange={e => setSettings({ ...settings, min_fee_cents: Math.round(parseFloat(e.target.value) * 100) })}
                                        />
                                    </div>
                                </div>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Frete Grátis acima de</label>
                                <div className="relative">
                                    <span className="absolute left-3 top-2 text-gray-500">R$</span>
                                    <input
                                        type="number"
                                        className="w-full pl-8 p-2 border rounded"
                                        value={((settings.free_shipping_threshold_cents || 0) / 100).toFixed(2)}
                                        onChange={e => setSettings({ ...settings, free_shipping_threshold_cents: Math.round(parseFloat(e.target.value) * 100) })}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* MAP AREA */}
                        <div className="mt-6 h-64 w-full rounded-lg overflow-hidden border border-gray-300 relative z-0">
                            {settings.latitude !== 0 && (
                                <MapContainer center={center} zoom={13} style={{ height: '100%', width: '100%' }}>
                                    <TileLayer
                                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                                        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                                    />
                                    <Marker position={center}>
                                        <Popup>Sua Loja</Popup>
                                    </Marker>
                                    {settings.active && (
                                        <Circle
                                            center={center}
                                            radius={settings.max_radius_km * 1000}
                                            pathOptions={{ fillColor: 'blue', color: 'blue', opacity: 0.5 }}
                                        />
                                    )}
                                    {settings.active && (
                                        <RadiusController
                                            center={center}
                                            setRadius={(r) => setSettings(s => ({ ...s, max_radius_km: r }))}
                                        />
                                    )}
                                </MapContainer>
                            )}
                        </div>
                    </div>

                    {/* Pickup Settings */}
                    <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 h-fit">
                        <div className="flex items-center justify-between mb-4">
                            <h2 className="text-lg font-semibold flex items-center gap-2">
                                <FaStore size={18} color="black" />
                                Retirada na Loja
                            </h2>
                            <label className="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" className="sr-only peer" checked={settings.pickup_active} onChange={e => setSettings({ ...settings, pickup_active: e.target.checked })} />
                                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-emerald-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-emerald-600"></div>
                                <span className="ml-3 text-sm font-medium text-gray-900">{settings.pickup_active ? 'Ativado' : 'Desativado'}</span>
                            </label>
                        </div>

                        <div className={`space-y-4 ${!settings.pickup_active && 'opacity-50 pointer-events-none'}`}>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Endereço de Retirada</label>
                                <textarea
                                    className="w-full p-2 border rounded h-24"
                                    placeholder="Rua Exemplo, 123 - Bairro..."
                                    value={settings.pickup_address}
                                    onChange={e => setSettings({ ...settings, pickup_address: e.target.value })}
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">Horário de Retirada</label>
                                <input
                                    type="text"
                                    className="w-full p-2 border rounded"
                                    placeholder="Seg-Sex 08:00 às 18:00..."
                                    value={settings.pickup_hours}
                                    onChange={e => setSettings({ ...settings, pickup_hours: e.target.value })}
                                />
                            </div>
                            <div className="bg-blue-50 p-4 rounded-lg flex gap-3 text-sm" style={{ color: '#0F4C81' }}>
                                <FaCircleInfo size={18} className="flex-shrink-0 mt-0.5" />
                                <p>Ao ativar a retirada, os clientes poderão escolher buscar o pedido na loja sem custo de frete.</p>
                            </div>
                        </div>
                    </div>
                </form>

                <div className="flex justify-end pt-4 border-t">
                    <button
                        onClick={handleSave}
                        disabled={saving}
                        className="flex items-center gap-2 px-6 py-2.5 rounded-lg font-semibold text-white hover:opacity-90 transition disabled:opacity-50"
                        style={{ backgroundColor: '#0F4C81' }}
                    >
                        <FaFloppyDisk size={16} color="white" />
                        {saving ? 'Salvando...' : 'Salvar Configurações'}
                    </button>
                </div>
            </div>
        </Shell>
    )
}
