'use client'

import { useEffect, useState } from 'react'
import { Card, CardHeader, CardContent, TextField, Stack, Typography, CircularProgress } from '@mui/material'
import Button from '@/@core/components/mui/Button'
import { useTranslations } from 'next-intl'
import { useGetEntityProfile } from '@/@core/hooks/data/profile'
import { useUpdateContactInfo } from '@/@core/hooks/data/profile/useUpdateContactInfo'
import { useSnackbar } from 'notistack'
import { MapContainer, TileLayer, Marker, useMapEvents } from 'react-leaflet'
import L from 'leaflet'

delete (L.Icon.Default.prototype as any)._getIconUrl
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
  iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
  shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png'
})

export default function ContactInfoCard() {
  const t = useTranslations('PROFILE')
  const { enqueueSnackbar } = useSnackbar()
  const { data, refetch } = useGetEntityProfile()
  const profile = data?.data

  const [editMode, setEditMode] = useState(false)
  const [form, setForm] = useState({
    phone: '',
    email: '',
    address_ar: '',
    address_en: '',
    latitude: 24.7136,
    longitude: 46.6753
  })

  useEffect(() => {
    if (profile) {
      setForm({
        phone: profile.phone || '',
        email: profile.email || '',
        address_ar: profile.address_ar || '',
        address_en: profile.address_en || '',
        latitude: profile.latitude || 24.7136,
        longitude: profile.longitude || 46.6753
      })
    }
  }, [profile])

  const { mutate, isPending } = useUpdateContactInfo()

  const handleChange = (field: string, value: any) => {
    setForm(prev => ({ ...prev, [field]: value }))
  }

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    mutate(form, {
      onSuccess: () => {
        enqueueSnackbar(t('contact.successMessage'), { variant: 'success' })
        refetch()
        setEditMode(false)
      },
      onError: (error: any) => {
        enqueueSnackbar(error?.message || t('contact.errorMessage'), { variant: 'error' })
      }
    })
  }

  function LocationMarker() {
    useMapEvents({
      click(e: any) {
        if (editMode) {
          handleChange('latitude', e.latlng.lat)
          handleChange('longitude', e.latlng.lng)
        }
      }
    })
    return <Marker position={[form.latitude, form.longitude]} />
  }

  if (!profile) return <Typography>{t('loading')}</Typography>

  return (
    <Card className='rounded-xl shadow-sm border border-gray-200 h-full'>
      <CardHeader
        title={t('contact.title')}
        action={
          editMode ? (
            <Stack direction='row' spacing={1}>
              <Button size='small' variant='outlined' onClick={() => setEditMode(false)} disabled={isPending}>
                {t('cancel')}
              </Button>
              <Button
                size='small'
                variant='contained'
                type='submit'
                form='contact-form'
                disabled={isPending}
                startIcon={isPending ? <CircularProgress size={16} color='inherit' /> : null}
              >
                {isPending ? t('saving') : t('save')}
              </Button>
            </Stack>
          ) : (
            <Button size='small' onClick={() => setEditMode(true)}>
              {t('edit')}
            </Button>
          )
        }
      />

      <CardContent className='space-y-3'>
        {editMode ? (
          <form id='contact-form' onSubmit={handleSubmit}>
            <Stack spacing={2}>
              <TextField
                label={t('contact.phone')}
                value={form.phone}
                onChange={e => handleChange('phone', e.target.value)}
                fullWidth
              />
              <TextField
                label={t('contact.email')}
                value={form.email}
                onChange={e => handleChange('email', e.target.value)}
                fullWidth
              />
              <TextField
                label={t('contact.addressAr')}
                value={form.address_ar}
                onChange={e => handleChange('address_ar', e.target.value)}
                fullWidth
              />
              <TextField
                label={t('contact.addressEn')}
                value={form.address_en}
                onChange={e => handleChange('address_en', e.target.value)}
                fullWidth
              />

              <Stack direction='row' spacing={2}>
                <TextField
                  label={t('contact.latitude')}
                  type='number'
                  value={form.latitude}
                  onChange={e => handleChange('latitude', parseFloat(e.target.value))}
                  fullWidth
                />
                <TextField
                  label={t('contact.longitude')}
                  type='number'
                  value={form.longitude}
                  onChange={e => handleChange('longitude', parseFloat(e.target.value))}
                  fullWidth
                />
              </Stack>

              {/* 🗺️ الخريطة التفاعلية */}
              <div className='rounded-md overflow-hidden border h-72'>
                <MapContainer
                  {...({
                    center: [form.latitude, form.longitude],
                    zoom: 13,
                    style: { width: '100%', height: '100%' }
                  } as any)}
                >
                  <TileLayer
                    {...({
                      attribution: '&copy; OpenStreetMap contributors',
                      url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
                    } as any)}
                  />
                  <LocationMarker />
                </MapContainer>
              </div>
            </Stack>
          </form>
        ) : (
          <>
            <Typography>
              <strong>{t('contact.phone')}</strong> {profile.phone}
            </Typography>
            <Typography>
              <strong>{t('contact.email')}</strong> {profile.email}
            </Typography>
            <Typography>
              <strong>{t('contact.addressAr')}</strong> {profile.address_ar}
            </Typography>
            <Typography>
              <strong>{t('contact.addressEn')}</strong> {profile.address_en}
            </Typography>
            <Typography>
              <strong>{t('contact.latitude')}</strong> {profile.latitude}
            </Typography>
            <Typography>
              <strong>{t('contact.longitude')}</strong> {profile.longitude}
            </Typography>

            <div className='rounded-md overflow-hidden border h-72 mt-3'>
              <MapContainer
                {...({
                  center: [profile.latitude, profile.longitude],
                  zoom: 13,
                  style: { width: '100%', height: '100%' }
                } as any)}
              >
                <TileLayer
                  {...({
                    attribution: '&copy; OpenStreetMap contributors',
                    url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
                  } as any)}
                />
                <Marker position={[profile.latitude, profile.longitude]} />
              </MapContainer>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  )
}
