'use client'

// React Imports
import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import type { ChangeEvent } from 'react'

// MUI Imports
import Grid from '@mui/material/Grid2'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import CircularProgress from '@mui/material/CircularProgress'
import Box from '@mui/material/Box'

// Component Imports
import CustomTextField from '@core/components/mui/TextField'

// API Imports
import { userManagementService } from '@/libs/api'
import { useAuth } from '@/contexts/authContext'

type Data = {
  firstName: string
  lastName: string
  email: string
  phoneNumber: number | string
}

// Vars
const initialData: Data = {
  firstName: '',
  lastName: '',
  email: '',
  phoneNumber: ''
}

const AccountDetails = () => {
  const t = useTranslations('accountSettings')
  const { user: authUser } = useAuth()

  // States
  const [formData, setFormData] = useState<Data>(initialData)
  const [fileInput, setFileInput] = useState<string>('')
  const [imgSrc, setImgSrc] = useState<string>('/images/avatars/1.png')
  const [loading, setLoading] = useState<boolean>(true)
  const [saving, setSaving] = useState<boolean>(false)
  const [error, setError] = useState<string | null>(null)

  // Load user data from auth context (profile uses first_name, last_name, email, phone_number)
  useEffect(() => {
    if (!authUser) {
      setLoading(false)
      return
    }

    setFormData({
      firstName: authUser.first_name || '',
      lastName: authUser.last_name || '',
      email: authUser.email || '',
      phoneNumber: authUser.phone_number || ''
    })
    setLoading(false)
  }, [authUser])

  const handleFormChange = (field: keyof Data, value: Data[keyof Data]) => {
    setFormData({ ...formData, [field]: value })
  }

  const handleFileInputChange = (file: ChangeEvent) => {
    const reader = new FileReader()
    const { files } = file.target as HTMLInputElement

    if (files && files.length !== 0) {
      reader.onload = () => setImgSrc(reader.result as string)
      reader.readAsDataURL(files[0])

      if (reader.result !== null) {
        setFileInput(reader.result as string)
      }
    }
  }

  const handleFileInputReset = () => {
    setFileInput('')
    setImgSrc('/images/avatars/1.png')
  }

  const handleSubmit = async () => {
    if (!authUser) return
    try {
      setSaving(true)
      setError(null)
      await userManagementService.updateProfile({
        first_name: formData.firstName,
        last_name: formData.lastName,
        email: formData.email
      })
      // Refresh auth user data - caller would need to update context; for now form stays as-is
    } catch (err: any) {
      setError(err.message || t('errorSave'))
    } finally {
      setSaving(false)
    }
  }

  const handleReset = () => {
    if (authUser) {
      setFormData({
        firstName: authUser.first_name || '',
        lastName: authUser.last_name || '',
        email: authUser.email || '',
        phoneNumber: authUser.phone_number || ''
      })
    }
  }

  if (loading) {
    return (
      <Card>
        <CardContent>
          <Box className='flex items-center justify-center' sx={{ minHeight: 200 }}>
            <CircularProgress />
          </Box>
        </CardContent>
      </Card>
    )
  }

  if (error) {
    return (
      <Card>
        <CardContent>
          <Box className='flex items-center justify-center' sx={{ minHeight: 200 }}>
            <Typography color='error'>{error}</Typography>
          </Box>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      {/* <CardContent className='mbe-4'>
        <div className='flex max-sm:flex-col items-center gap-6'>
          <img height={100} width={100} className='rounded' src={imgSrc} alt='Profile' />
          <div className='flex flex-grow flex-col gap-4'>
            <div className='flex flex-col sm:flex-row gap-4'>
              <Button component='label' variant='contained' htmlFor='account-settings-upload-image'>
                Upload New Photo
                <input
                  hidden
                  type='file'
                  value={fileInput}
                  accept='image/png, image/jpeg'
                  onChange={handleFileInputChange}
                  id='account-settings-upload-image'
                />
              </Button>
              <Button variant='tonal' color='secondary' onClick={handleFileInputReset}>
                Reset
              </Button>
            </div>
            <Typography>Allowed JPG, GIF or PNG. Max size of 800K</Typography>
          </div>
        </div>
      </CardContent> */}
      <CardContent>
        <form onSubmit={e => { e.preventDefault(); handleSubmit() }}>
          <Grid container spacing={6}>
            <Grid size={{ xs: 12, sm: 6 }}>
              <CustomTextField
                fullWidth
                label={t('firstName')}
                value={formData.firstName}
                placeholder={t('placeholderFirstName')}
                onChange={e => handleFormChange('firstName', e.target.value)}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <CustomTextField
                fullWidth
                label={t('lastName')}
                value={formData.lastName}
                placeholder={t('placeholderLastName')}
                onChange={e => handleFormChange('lastName', e.target.value)}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <CustomTextField
                fullWidth
                label={t('email')}
                value={formData.email}
                placeholder={t('placeholderEmail')}
                onChange={e => handleFormChange('email', e.target.value)}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <CustomTextField
                fullWidth
                label={t('phoneNumber')}
                value={formData.phoneNumber}
                placeholder={t('placeholderPhone')}
                onChange={e => handleFormChange('phoneNumber', e.target.value)}
              />
            </Grid>
            <Grid size={{ xs: 12 }} className='flex gap-4 flex-wrap'>
              <Button variant='contained' type='submit' disabled={saving}>
                {saving ? t('saving') : t('saveChanges')}
              </Button>
              <Button variant='tonal' type='button' color='secondary' onClick={handleReset}>
                {t('reset')}
              </Button>
            </Grid>
          </Grid>
        </form>
      </CardContent>
    </Card>
  )
}

export default AccountDetails
