'use client'
import React, { useState, useEffect, useRef, useCallback } from 'react'
import { useForm } from 'react-hook-form'
import { Button } from '@/components/ui/button'
import Input from '@/components/Input'
import { Location, TickCircle, CloseCircle, ArrowRight2, ArrowLeft2 } from 'iconsax-react'
import DefaulModal from '@/components/DefaulModal'
import { useGetAddressByLocation, useUpdateAddress } from '../hooks/useProfileData'
import { UpdateAddressType } from '../types/ProfileTypes'
import type { Map as LeafletMap, LeafletMouseEvent, Marker } from 'leaflet'

interface AddressModalProps {
    isOpen: boolean
    onClose: () => void
    currentAddress?: string
    onAddressChange: (addressData: UpdateAddressType) => void
}

const AddressModal: React.FC<AddressModalProps> = ({
    isOpen,
    onClose,
    onAddressChange
}) => {
    const [currentStep, setCurrentStep] = useState(1)
    const [selectedLocation, setSelectedLocation] = useState<{ lat: number; lng: number } | null>(null)
    const [isMapLoaded, setIsMapLoaded] = useState(false)
    const mapRef = useRef<HTMLDivElement>(null)
    const leafletMapRef = useRef<LeafletMap | null>(null)
    const currentMarkerRef = useRef<Marker | null>(null)

    // React Hook Form
    const { register, handleSubmit, setValue, formState: { errors, isSubmitting } } = useForm<UpdateAddressType>({
        defaultValues: {
            lat: '',
            lon: '',
            provinceId: 0,
            cityId: 0,
            postalCode: '',
            address: '',
            plaque: ''
        }
    })

    // Get address by location
    const { data: addressData, isLoading: isLoadingAddress } = useGetAddressByLocation(
        selectedLocation?.lat,
        selectedLocation?.lng
    )

    // Update address mutation
    const updateAddressMutation = useUpdateAddress()

    const loadMap = useCallback(async () => {
        try {
            const L = await import('leaflet')

            // Fix default icon issue
            delete (L.Icon.Default.prototype as unknown as { _getIconUrl: unknown })._getIconUrl
            L.Icon.Default.mergeOptions({
                iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
                iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
                shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
            })

            if (mapRef.current && !leafletMapRef.current) {
                // Get initial coordinates (user's location or default to Tehran)
                const initialLat = selectedLocation?.lat || 35.6892
                const initialLng = selectedLocation?.lng || 51.3890

                // Create map
                leafletMapRef.current = L.map(mapRef.current).setView([initialLat, initialLng], 13)

                // Add tile layer
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                }).addTo(leafletMapRef.current)

                // Add click handler
                leafletMapRef.current.on('click', (e: LeafletMouseEvent) => {
                    const { lat, lng } = e.latlng
                    handleMapClick(lat, lng)
                })

                setIsMapLoaded(true)
            }
        } catch (error) {
            console.error('Error loading map:', error)
        }
    }, [selectedLocation?.lat, selectedLocation?.lng])

    useEffect(() => {
        if (isOpen && typeof window !== 'undefined' && !isMapLoaded) {
            loadMap()
        }
    }, [isOpen, isMapLoaded, loadMap])

    // Get user's current location on mount
    useEffect(() => {
        if (isOpen && navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const { latitude, longitude } = position.coords
                    setSelectedLocation({ lat: latitude, lng: longitude })
                },
                (error) => {
                    console.error('Error getting current location:', error)
                    // Fallback to Tehran coordinates
                    setSelectedLocation({ lat: 35.6892, lng: 51.3890 })
                }
            )
        }
    }, [isOpen])

    // Update map view when selectedLocation changes
    useEffect(() => {
        if (leafletMapRef.current && selectedLocation) {
            leafletMapRef.current.setView([selectedLocation.lat, selectedLocation.lng], 13)
        }
    }, [selectedLocation])

    const handleMapClick = async (lat: number, lng: number) => {
        // Add marker if map exists
        if (leafletMapRef.current) {
            const L = await import('leaflet')

            // Remove existing marker
            if (currentMarkerRef.current) {
                leafletMapRef.current.removeLayer(currentMarkerRef.current)
            }

            // Add new marker
            currentMarkerRef.current = L.marker([lat, lng]).addTo(leafletMapRef.current)
            currentMarkerRef.current.bindPopup(`
                <div style="text-align: center; padding: 8px;">
                    <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 8px;">
                        <span style="color: #16a34a; font-weight: 500;">آدرس شما اینجاست!</span>
                    </div>
                </div>
            `).openPopup()
        }

        // Set selected location
        setSelectedLocation({ lat, lng })
    }

    // Update form data when address data is received
    useEffect(() => {
        if (addressData?.results) {
            setValue('address', addressData.results.address)
            setValue('provinceId', addressData.results.provinceId)
            setValue('cityId', addressData.results.cityId)
        }
    }, [addressData, setValue])

    const handleNextStep = () => {
        if (selectedLocation) {
            setCurrentStep(2)
        }
    }

    const handlePrevStep = () => {
        setCurrentStep(1)
    }

    const onSubmit = async (data: UpdateAddressType) => {
        if (selectedLocation) {
            try {
                // Prepare data for API
                const updateData: UpdateAddressType = {
                    ...data,
                    lat: selectedLocation.lat.toString(),
                    lon: selectedLocation.lng.toString()
                }

                // Call update address API
                await updateAddressMutation.mutateAsync(updateData)

                // Call parent callback with form data
                onAddressChange(updateData)
                handleClose()
            } catch (error) {
                console.error('Error updating address:', error)
                // You can add toast notification here
            }
        }
    }

    const handleClose = () => {
        // Reset state when closing
        setCurrentStep(1)
        setSelectedLocation(null)
        // Reset form
        setValue('lat', '')
        setValue('lon', '')
        setValue('provinceId', 0)
        setValue('cityId', 0)
        setValue('postalCode', '')
        setValue('address', '')
        setValue('plaque', '')
        onClose()
    }

    const handleCurrentLocation = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const { latitude, longitude } = position.coords
                    handleMapClick(latitude, longitude)

                    // Pan map to current location
                    if (leafletMapRef.current) {
                        leafletMapRef.current.setView([latitude, longitude], 16)
                    }
                },
                (error) => {
                    console.error('Error getting location:', error)
                    alert('خطا در دریافت موقعیت فعلی')
                }
            )
        } else {
            alert('مرورگر شما از موقعیت‌یابی پشتیبانی نمی‌کند')
        }
    }

    const handleClearSelection = () => {
        setSelectedLocation(null)

        // Remove marker from map
        if (leafletMapRef.current && currentMarkerRef.current) {
            leafletMapRef.current.removeLayer(currentMarkerRef.current)
            currentMarkerRef.current = null
        }
    }

    // Cleanup on unmount
    useEffect(() => {
        return () => {
            if (leafletMapRef.current) {
                leafletMapRef.current.remove()
                leafletMapRef.current = null
            }
        }
    }, [])

    const renderStep1 = () => (
        <div className="flex flex-col h-full">
            {/* Subtitle */}
            <p className="text-sm text-gray-600 mb-4 text-center">
                موقعیت خود را روی نقشه انتخاب کنید
            </p>

            {/* Selected Location Display */}
            {selectedLocation && (
                <div className="mt-4 p-4 bg-gradient-to-r from-green-50 to-primary/10 rounded-lg border border-green-200">
                    <div className="flex items-start gap-3">
                        <div className="flex-shrink-0 mt-0.5">
                            <TickCircle size={20} className="text-green-600" />
                        </div>
                        <div className="flex-1">
                            <div className="flex items-center justify-between mb-2">
                                <span className="text-sm font-medium text-green-800">موقعیت انتخاب شده:</span>
                                <button
                                    onClick={handleClearSelection}
                                    className="text-red-400 hover:text-red-600 transition-colors"
                                >
                                    <CloseCircle size={16} />
                                </button>
                            </div>
                            <p className="text-sm text-gray-700 leading-relaxed">
                                {isLoadingAddress ? 'در حال دریافت آدرس...' :
                                    addressData?.results?.address ||
                                    `عرض جغرافیایی: ${selectedLocation.lat.toFixed(6)}, طول جغرافیایی: ${selectedLocation.lng.toFixed(6)}`}
                            </p>
                        </div>
                    </div>
                </div>
            )}

            {/* Action Buttons */}
            <div className="flex flex-col sm:flex-row gap-3 justify-end mt-6">
                <Button
                    onClick={handleClose}
                    variant="outline"
                    className="w-full sm:w-auto order-2 sm:order-1"
                >
                    انصراف
                </Button>
                <Button
                    onClick={handleNextStep}
                    className="w-full sm:w-auto bg-primary hover:bg-primary/90 order-1 sm:order-2 disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={!selectedLocation}
                >
                    مرحله بعد
                    <ArrowLeft2 size={20} color='white' className="mr-1" />
                </Button>
            </div>
        </div>
    )

    const renderStep2 = () => (
        <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col h-full">
            {/* Subtitle */}
            <p className="text-sm text-gray-600 mb-4 text-center">
                آدرس جدید خود را وارد کنید
            </p>

            {/* Address Form */}
            <div className="flex-1 space-y-4">
                {/* Main Address Field */}
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        آدرس کامل
                    </label>
                    <textarea
                        {...register('address', { required: 'آدرس کامل الزامی است' })}
                        className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
                        rows={4}
                        placeholder="آدرس کامل خود را وارد کنید"
                    />
                    {errors.address && (
                        <p className="text-red-500 text-sm mt-1">{errors.address.message}</p>
                    )}
                </div>

                {/* Province and City Row - Readonly */}
                <div className="grid grid-cols-2 gap-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            شهر
                        </label>
                        <Input
                            value={addressData?.results?.city || ''}
                            readOnly
                            className="w-full bg-gray-50 cursor-not-allowed"
                            placeholder="شهر"
                        />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            استان
                        </label>
                        <Input
                            value={addressData?.results?.province || ''}
                            readOnly
                            className="w-full bg-gray-50 cursor-not-allowed"
                            placeholder="استان"
                        />
                    </div>
                </div>

                {/* Postal Code and Plaque Row */}
                <div className="grid grid-cols-2 gap-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            کد پستی
                        </label>
                        <Input
                            {...register('postalCode', { required: 'کد پستی الزامی است' })}
                            placeholder="کد پستی"
                            className="w-full"
                        />
                        {errors.postalCode && (
                            <p className="text-red-500 text-sm mt-1">{errors.postalCode.message}</p>
                        )}
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            پلاک
                        </label>
                        <Input
                            {...register('plaque', { required: 'پلاک الزامی است' })}
                            placeholder="پلاک"
                            className="w-full"
                        />
                        {errors.plaque && (
                            <p className="text-red-500 text-sm mt-1">{errors.plaque.message}</p>
                        )}
                    </div>
                </div>
            </div>

            {/* Action Buttons */}
            <div className="flex flex-col sm:flex-row gap-3 justify-end mt-6">
                <Button
                    type="button"
                    onClick={handlePrevStep}
                    variant="outline"
                    className="w-full sm:w-auto order-2 sm:order-1"
                >
                    <ArrowRight2 color='black' size={16} className="ml-1" />
                    مرحله قبل
                </Button>
                <Button
                    type="button"
                    onClick={handleClose}
                    variant="outline"
                    className="w-full sm:w-auto order-3 sm:order-2"
                >
                    انصراف
                </Button>
                <Button
                    type="submit"
                    className="w-full sm:w-auto bg-primary hover:bg-primary/90 order-1 sm:order-3 disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={isSubmitting || updateAddressMutation.isPending}
                >
                    <TickCircle color='white' size={16} className="ml-1" />
                    {isSubmitting || updateAddressMutation.isPending ? 'در حال ذخیره...' : 'تایید'}
                </Button>
            </div>
        </form>
    )

    return (
        <DefaulModal
            open={isOpen}
            close={handleClose}
            isHeader={true}
            title_header="تغییر آدرس"
            width={500}
        >
            {/* Map Container - Only show in step 1 */}
            {currentStep === 1 && (
                <div className="flex-1 relative rounded-lg overflow-hidden border border-gray-200 bg-gray-100 min-h-[300px]">
                    <div
                        ref={mapRef}
                        className="h-full w-full rounded-lg"
                        style={{ minHeight: '300px' }}
                    />

                    {!isMapLoaded && (
                        <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
                            <div className="text-center text-gray-500">
                                <Location size={48} color="#015699" className="mx-auto mb-4" />
                                <p className="text-lg">در حال بارگذاری نقشه...</p>
                            </div>
                        </div>
                    )}

                    {/* Current Location Button Overlay */}
                    <div className="absolute bottom-4 left-4 z-[1000]">
                        <Button
                            onClick={handleCurrentLocation}
                            variant="outline"
                            size="sm"
                        >
                            <Location color={'black'} size={20} className="ml-0.5" />
                            موقعیت فعلی
                        </Button>
                    </div>
                </div>
            )}

            {currentStep === 1 ? renderStep1() : renderStep2()}
        </DefaulModal>
    )
}

export default AddressModal