'use client'

import { useEffect, useState } from 'react'
import { Card, CardHeader, CardContent, Typography, Stack, CircularProgress } from '@mui/material'
import Button from '@/@core/components/mui/Button'
import { useTranslations } from 'next-intl'
import { useGetEntityProfile } from '@/@core/hooks/data/profile'
import { useUpdateWorkingHours } from '@/@core/hooks/data/profile/useUpdateWorkingHours'
import { useSnackbar } from 'notistack'
import { LocalizationProvider, TimePicker } from '@mui/x-date-pickers'
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
import dayjs, { Dayjs } from 'dayjs'

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

  const [hours, setHours] = useState<Record<string, [string, string]>>({})
  const [editMode, setEditMode] = useState(false)

  useEffect(() => {
    if (profile?.working_hours) {
      setHours(profile.working_hours as any)
    }
  }, [profile])

  const { mutate, isPending } = useUpdateWorkingHours()

  const handleChange = (day: string, index: number, value: string) => {
    setHours(prev => ({
      ...prev,
      [day]: index === 0 ? [value, prev[day]?.[1] || ''] : [prev[day]?.[0] || '', value]
    }))
  }

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    mutate(
      { working_hours: hours },
      {
        onSuccess: () => {
          enqueueSnackbar(t('workingHours.successMessage'), { variant: 'success' })
          refetch()
          setEditMode(false)
        },
        onError: () => {
          enqueueSnackbar(t('workingHours.errorMessage'), { variant: 'error' })
        }
      }
    )
  }

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

  const days = ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday']

  return (
    <Card className='rounded-xl shadow-sm border border-gray-200 h-full'>
      <CardHeader
        title={t('workingHours.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='working-hours-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>
        {editMode ? (
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <form id='working-hours-form' onSubmit={handleSubmit}>
              <Stack spacing={2}>
                {days.map(day => (
                  <Stack key={day} direction='row' alignItems='center' spacing={2}>
                    <Typography className='capitalize w-24'>{t(`workingHours.days.${day}`)}</Typography>
                    <TimePicker
                      label={t('workingHours.start')}
                      value={
                        hours[day]?.[0] ? dayjs(`2024-01-01T${hours[day][0]}`) : (dayjs('2024-01-01T10:00') as Dayjs)
                      }
                      onChange={v => handleChange(day, 0, v?.format('HH:mm') || '00:00')}
                    />
                    <TimePicker
                      label={t('workingHours.end')}
                      value={
                        hours[day]?.[1] ? dayjs(`2024-01-01T${hours[day][1]}`) : (dayjs('2024-01-01T02:00') as Dayjs)
                      }
                      onChange={v => handleChange(day, 1, v?.format('HH:mm') || '00:00')}
                    />
                  </Stack>
                ))}
              </Stack>
            </form>
          </LocalizationProvider>
        ) : (
          <Stack spacing={1}>
            {days.map(day => (
              <Typography key={day}>
                <strong className='capitalize'>{t(`workingHours.days.${day}`)}:</strong> {hours[day]?.[0]} -{' '}
                {hours[day]?.[1]}
              </Typography>
            ))}
          </Stack>
        )}
      </CardContent>
    </Card>
  )
}
