'use client'

import { useEffect, useState } from 'react'
import { Card, CardHeader, CardContent, TextField, Stack, Typography, CircularProgress, Slider } from '@mui/material'
import Button from '@/@core/components/mui/Button'
import { useTranslations } from 'next-intl'
import { useGetEntityProfile } from '@/@core/hooks/data/profile'
import { useUpdateLocationInfo } from '@/@core/hooks/data/profile/useUpdateLocationInfo'
import { useSnackbar } from 'notistack'

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

  const [editMode, setEditMode] = useState(false)
  const [form, setForm] = useState({
    delivery_fee: profile?.delivery_fee || 0,
    minimum_order: profile?.minimum_order || 0,
    delivery_radius: profile?.delivery_radius || 5,
    preparation_time: profile?.preparation_time || 15
  })

  const { mutate, isPending } = useUpdateLocationInfo()

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

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

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

  return (
    <Card className='rounded-xl shadow-sm border border-gray-200 h-full'>
      <CardHeader
        title={t('location.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='location-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='location-form' onSubmit={handleSubmit}>
            <Stack spacing={2}>
              <TextField
                label={t('location.deliveryFee')}
                value={form.delivery_fee}
                onChange={e => handleChange('delivery_fee', parseFloat(e.target.value))}
                type='number'
              />
              <TextField
                label={t('location.minOrder')}
                value={form.minimum_order}
                onChange={e => handleChange('minimum_order', parseFloat(e.target.value))}
                type='number'
              />
              <TextField
                label={t('location.prepTime')}
                value={form.preparation_time}
                onChange={e => handleChange('preparation_time', parseFloat(e.target.value))}
                type='number'
              />

              <Typography>
                {t('location.radius')}: {form.delivery_radius} km
              </Typography>
              <Slider
                value={form.delivery_radius as any}
                onChange={(_, val) => handleChange('delivery_radius', val)}
                min={1}
                max={50}
                step={1}
                valueLabelDisplay='auto'
              />
            </Stack>
          </form>
        ) : (
          <>
            <Typography>
              <strong>{t('location.deliveryFee')}</strong> {profile.delivery_fee} SAR
            </Typography>
            <Typography>
              <strong>{t('location.minOrder')}</strong> {profile.minimum_order} SAR
            </Typography>
            <Typography>
              <strong>{t('location.prepTime')}</strong> {profile.preparation_time} mins
            </Typography>
            <Typography>
              <strong>{t('location.radius')}</strong> {profile.delivery_radius} km
            </Typography>
          </>
        )}
      </CardContent>
    </Card>
  )
}
