/* eslint-disable */
'use client'

import {
  Box,
  Button,
  Card,
  CardContent,
  Divider,
  IconButton,
  Stack,
  TextField,
  Typography,
  Select,
  MenuItem,
  InputLabel,
  FormControl
} from '@mui/material'
import CloseIcon from '@mui/icons-material/Close'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import { loadDoctors, updateDoctor } from '@/libs/admin/doctor'
import Notification from '@/app/admin/notification'
import { loadCategory, getCategories } from '@/libs/admin/category'
import { log } from 'console'
import { getSubCategories } from '@/libs/admin/subcategory'

interface DoctorDetails {
  specializationInfo: {
    _id: string
    categoryName: string
  }
  subSpecializationInfo: {
    _id: string
    subCategoryName: string
  }
}

const EditDoctorPage = ({ params }: { params: { id: string } }) => {
  const [doctor, setDoctor] = useState<DoctorDetails | null>(null)
  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [gender, setGender] = useState('')
  const [dob, setDob] = useState('')
  const [profilePicture, setProfilePicture] = useState<File | null>(null)
  const [imgSrc, setImgSrc] = useState('/images/default/images.jpg') // Default image
  const [fileInput, setFileInput] = useState('') // To control the input value
  const [phoneNumber, setPhoneNumber] = useState('')
  const [email, setEmail] = useState('')
  const [address, setAddress] = useState('')
  const [street, setStreet] = useState('')
  const [city, setCity] = useState('')
  const [state, setState] = useState('')
  const [postalCode, setPostalCode] = useState('')
  const [country, setCountry] = useState('')
  const [website, setWebsite] = useState('')

  const [specialization, setSpecialization] = useState('')
  const [subSpecialization, setSubSpecialization] = useState('')
  const [licenseNumber, setLicenseNumber] = useState('')
  const [yearsOfExperience, setYearsOfExperience] = useState('')
  const [qualifications1InstitutionName, setqualifications1InstitutionName] = useState('')
  const [qualifications1YearOfCompletion, setqualifications1YearOfCompletion] = useState('')
  const [qualifications2InstitutionName, setqualifications2InstitutionName] = useState('')
  const [qualifications2YearOfCompletion, setqualifications2YearOfCompletion] = useState('')
  const [qualifications3InstitutionName, setqualifications3InstitutionName] = useState('')
  const [qualifications3YearOfCompletion, setqualifications3YearOfCompletion] = useState('')
  const [qualifications4InstitutionName, setqualifications4InstitutionName] = useState('')
  const [qualifications4YearOfCompletion, setqualifications4YearOfCompletion] = useState('')
  const [affiliations, setAffiliations] = useState('')
  const [languagesSpoken, setLanguagesSpoken] = useState('')
  // const [password, setPassword] = useState('')
  // const [confirmPassword, setConfirmPassword] = useState('')

  // New fields
  const [areasOfExpertise, setAreasOfExpertise] = useState('')
  const [awardsRecognitions, setAwardsRecognitions] = useState('')
  const [publicationsResearch, setPublicationsResearch] = useState('')
  const [categories, setCategories] = useState<any[]>([])
  const [selectedCategory, setSelectedCategory] = useState('')
  const [subCategories, setSubCategories] = useState<any[]>([])
  const [selectedSubCategory, setSelectedSubCategory] = useState('')
  const [socialMediaLinks, setSocialMediaLinks] = useState('')
  const [personalBio, setPersonalBio] = useState('')
  const [categoryList, setCategoryList] = useState<any[]>([])

  const [notificationMessage, setNotificationMessage] = useState('')
  const [isOpenNotification, setIsOpenNotification] = useState(false)

  const router = useRouter()

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await loadCategory()
        console.log('loadCategory', response)

        if (Array.isArray(response)) {
          // Transform category data to match the expected format
          const transformedCategories = response.map(category => ({
            id: category?._id.toString(),
            name: category?.categoryName
          }))
          setCategories(transformedCategories)
        }
      } catch (error) {
        setNotificationMessage('Error loading categories data')
        setIsOpenNotification(true)
      }
    }

    fetchCategories()
  }, [])

  useEffect(() => {
    const fetchSubCategories = async () => {
      if (selectedCategory) {
        const response = await getSubCategories()
        if (response.status === 1) {
          const filteredSubCategories = response.result.filter((subCat: any) => subCat.categoryId === selectedCategory)
          setSubCategories(filteredSubCategories)
        }
      }
    }
    fetchSubCategories()
  }, [selectedCategory])

  useEffect(() => {
    const fetchDoctor = async () => {
      try {
        const response = await loadDoctors(params.id)
        console.log('response', response)

        if (response && !response.error) {
          setFirstName(response.firstName || '')
          setLastName(response.lastName || '')
          setEmail(response.email || '')
          setPhoneNumber(response.phoneNumber || '')
          setGender(response.gender || '')
          setDob(response.dob || '')
          setAddress(response.address || '')
          setStreet(response.street || '')
          setCity(response.city || '')
          setState(response.state || '')
          setPostalCode(response.postalCode || '')
          setCountry(response.country || '')
          setWebsite(response.website || '')
          setSelectedCategory(response.specializationInfo?._id || '')
          setSelectedSubCategory(response.subSpecializationInfo?._id || '')
          setLicenseNumber(response.licenseNumber || '')
          setYearsOfExperience(response.yearsOfExperience || '')
          // Update the state setters to handle nested objects correctly
          setqualifications1InstitutionName(response.qualifications1?.institutionName || '')
          setqualifications1YearOfCompletion(response.qualifications1?.yearOfCompletion || '')

          setqualifications2InstitutionName(response.qualifications2?.institutionName || '')
          setqualifications2YearOfCompletion(response.qualifications2?.yearOfCompletion || '')

          setqualifications3InstitutionName(response.qualifications3?.institutionName || '')
          setqualifications3YearOfCompletion(response.qualifications3?.yearOfCompletion || '')

          setqualifications4InstitutionName(response.qualifications4?.institutionName || '')
          setqualifications4YearOfCompletion(response.qualifications4?.yearOfCompletion || '')

          setAffiliations(response.affiliations || '')
          setLanguagesSpoken(response.languagesSpoken || '')
          setAreasOfExpertise(response.areasOfExpertise || '')
          setAwardsRecognitions(response.awardsRecognitions || '')
          setPublicationsResearch(response.publicationsResearch || '')

          setSocialMediaLinks(response.socialMediaLinks || '')
          setPersonalBio(response.personalBio || '')
          if (!response.profilePicture || response.profilePicture === 'images.jpg') {
            setImgSrc('/images/default/images.jpg')
          } else {
            setImgSrc(`/uploads/doctor/${response.profilePicture}`)
          }
        } else {
          setNotificationMessage('Doctor not found')
          setIsOpenNotification(true)
        }
      } catch (error) {
        setNotificationMessage('Error loading doctor data')
        setIsOpenNotification(true)
      }
    }

    if (params.id) {
      fetchDoctor()
    }
  }, [params.id])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // if (password !== confirmPassword) {
    //   setNotificationMessage('Passwords do not match!')
    //   setIsOpenNotification(true)
    //   return
    // }

    const formData = new FormData()
    if (profilePicture) formData.append('profilePicture', profilePicture)
    formData.append('firstName', firstName)
    formData.append('lastName', lastName)
    formData.append('gender', gender)
    formData.append('dob', dob)
    formData.append('phoneNumber', phoneNumber)
    formData.append('email', email)
    formData.append('address', address)
    formData.append('street', street)
    formData.append('city', city)
    formData.append('state', state)
    formData.append('postalCode', postalCode)
    formData.append('country', country)
    formData.append('website', website)
    formData.append('specialization', selectedCategory)
    formData.append('subSpecialization', selectedSubCategory)
    formData.append('licenseNumber', licenseNumber)
    formData.append('yearsOfExperience', yearsOfExperience)

    formData.append('qualifications1InstitutionName', qualifications1InstitutionName || '')
    formData.append('qualifications1YearOfCompletion', qualifications1YearOfCompletion || '')

    formData.append('qualifications2InstitutionName', qualifications2InstitutionName || '')
    formData.append('qualifications2YearOfCompletion', qualifications2YearOfCompletion || '')

    formData.append('qualifications3InstitutionName', qualifications3InstitutionName || '')
    formData.append('qualifications3YearOfCompletion', qualifications3YearOfCompletion || '')

    formData.append('qualifications4InstitutionName', qualifications4InstitutionName || '')
    formData.append('qualifications4YearOfCompletion', qualifications4YearOfCompletion || '')

    formData.append('affiliations', affiliations)
    formData.append('languagesSpoken', languagesSpoken)
    formData.append('areasOfExpertise', areasOfExpertise)
    formData.append('awardsRecognitions', awardsRecognitions)
    formData.append('publicationsResearch', publicationsResearch)
    formData.append('categories', JSON.stringify(categories))
    formData.append('socialMediaLinks', socialMediaLinks)
    formData.append('personalBio', personalBio)
    formData.append('id', params.id)

    const response = await updateDoctor(formData)

    if (response.status === 1) {
      setNotificationMessage('Doctor updated successfully!')
      setIsOpenNotification(true)
      router.push('/admin/doctor')
    } else {
      setNotificationMessage(response.error || 'Update failed')
      setIsOpenNotification(true)
    }
  }

  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const reader = new FileReader()
    const { files } = e.target
    if (files && files.length !== 0) {
      setProfilePicture(files[0])
      reader.onload = () => setImgSrc(reader.result as string)
      reader.readAsDataURL(files[0])
      setFileInput(e.target.value)
    }
  }

  const handleFileInputReset = () => {
    setFileInput('')
    setProfilePicture(null)
    setImgSrc('/images/default/images.jpg')
  }

  return (
    <Card>
      <CardContent>
        <Stack direction='row' justifyContent='space-between' alignItems='center' mb={2}>
          <Typography variant='h5'>Edit Doctor</Typography>
          <IconButton onClick={() => router.push('/admin/doctor')}>
            <CloseIcon />
          </IconButton>
        </Stack>
        <form onSubmit={handleSubmit}>
          <Stack spacing={3}>
            {/* Profile Picture */}
            <Stack direction='row' alignItems='center' spacing={2}>
              <Box
                component='img'
                src={imgSrc}
                alt='Profile Picture'
                sx={{
                  width: 100,
                  height: 100,
                  borderRadius: '50%',
                  objectFit: 'cover'
                }}
              />
              <Box>
                <Button variant='contained' component='label' sx={{ mr: 2 }}>
                  Upload Image
                  <input type='file' hidden onChange={handleFileInputChange} />
                </Button>
                <Button variant='outlined' onClick={handleFileInputReset}>
                  Reset
                </Button>
              </Box>{' '}
            </Stack>
            {/* Personal Details */}
            <TextField label='First Name' fullWidth value={firstName} onChange={e => setFirstName(e.target.value)} />
            <TextField label='Last Name' fullWidth value={lastName} onChange={e => setLastName(e.target.value)} />
            <FormControl fullWidth>
              <InputLabel id='gender-label'>Gender</InputLabel>
              <Select labelId='gender-label' label='Gender' value={gender} onChange={e => setGender(e.target.value)}>
                <MenuItem value='Male'>Male</MenuItem>
                <MenuItem value='Female'>Female</MenuItem>
                <MenuItem value='Other'>Other</MenuItem>
              </Select>
            </FormControl>
            <TextField
              label='Date of Birth'
              fullWidth
              type='date'
              value={dob}
              onChange={e => setDob(e.target.value)}
              InputLabelProps={{ shrink: true }}
            />
            <TextField
              label='Phone Number'
              fullWidth
              value={phoneNumber}
              onChange={e => setPhoneNumber(e.target.value)}
            />
            <TextField label='Email' fullWidth type='email' value={email} onChange={e => setEmail(e.target.value)} />
            {/* <TextField
              type='password'
              label='Password'
              fullWidth
              value={password}
              onChange={e => setPassword(e.target.value)}
            />

            <TextField
              type='password'
              label='Confirm Password'
              fullWidth
              value={confirmPassword}
              onChange={e => setConfirmPassword(e.target.value)}
            /> */}
            <TextField label='Address' fullWidth value={address} onChange={e => setAddress(e.target.value)} />
            <TextField label='Street' fullWidth value={street} onChange={e => setStreet(e.target.value)} />
            <TextField label='City' fullWidth value={city} onChange={e => setCity(e.target.value)} />
            <TextField label='State' fullWidth value={state} onChange={e => setState(e.target.value)} />
            <TextField label='Postal Code' fullWidth value={postalCode} onChange={e => setPostalCode(e.target.value)} />
            <TextField label='Country' fullWidth value={country} onChange={e => setCountry(e.target.value)} />
            <TextField label='Website' fullWidth value={website} onChange={e => setWebsite(e.target.value)} />
            {/* Medical Details */}

            <FormControl fullWidth sx={{ mb: 3 }}>
              <InputLabel id='specialization-select-label'>
                Specialization<span>*</span>
              </InputLabel>
              <Select
                labelId='specialization-select-label'
                value={selectedCategory}
                onChange={e => setSelectedCategory(e.target.value)}
                label='Specialization'
                required
              >
                {categories.map(category => (
                  <MenuItem key={category.id || category._id} value={category.id || category._id}>
                    {category.categoryName || category.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            <FormControl fullWidth sx={{ mb: 3 }}>
              <InputLabel id='subcategory-select-label'>Sub-Specialization</InputLabel>
              <Select
                labelId='subcategory-select-label'
                value={selectedSubCategory}
                onChange={e => setSelectedSubCategory(e.target.value)}
                label='Sub-Specialization'
              >
                {subCategories.map(subcategory => (
                  <MenuItem key={subcategory.id} value={subcategory.id}>
                    {subcategory.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            <TextField
              label='License Number'
              fullWidth
              value={licenseNumber}
              onChange={e => setLicenseNumber(e.target.value)}
            />
            <TextField
              label='Years of Experience'
              fullWidth
              value={yearsOfExperience}
              onChange={e => setYearsOfExperience(e.target.value)}
            />
            {/* Qualifications Section */}
            <Typography variant='h6' gutterBottom>
              Qualifications
            </Typography>

            {/* Qualification 1 */}
            <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
              <TextField
                name='qualifications1InstitutionName'
                value={qualifications1InstitutionName}
                onChange={e => setqualifications1InstitutionName(e.target.value)}
                sx={{ width: '50%' }}
                label='Institution Name 1'
                variant='outlined'
              />
              <TextField
                name='qualifications1YearOfCompletion'
                value={qualifications1YearOfCompletion}
                onChange={e => setqualifications1YearOfCompletion(e.target.value)}
                sx={{ width: '50%' }}
                label='Year of Completion 1'
                variant='outlined'
                // type='number'
              />
            </Box>

            {/* Qualification 2 */}
            <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
              <TextField
                name='qualifications2InstitutionName'
                value={qualifications2InstitutionName}
                onChange={e => setqualifications2InstitutionName(e.target.value)}
                sx={{ width: '50%' }}
                label='Institution Name 2'
                variant='outlined'
              />
              <TextField
                name='qualifications2YearOfCompletion'
                value={qualifications2YearOfCompletion}
                onChange={e => setqualifications2YearOfCompletion(e.target.value)}
                sx={{ width: '50%' }}
                label='Year of Completion 2'
                variant='outlined'
                // type='number'
              />
            </Box>

            {/* Qualification 3 */}
            <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
              <TextField
                name='qualifications3InstitutionName'
                value={qualifications3InstitutionName}
                onChange={e => setqualifications3InstitutionName(e.target.value)}
                sx={{ width: '50%' }}
                label='Institution Name 3'
                variant='outlined'
              />
              <TextField
                name='qualifications3YearOfCompletion'
                value={qualifications3YearOfCompletion}
                onChange={e => setqualifications3YearOfCompletion(e.target.value)}
                sx={{ width: '50%' }}
                label='Year of Completion 3'
                variant='outlined'
                // type='number'
              />
            </Box>

            {/* Qualification 4 */}
            <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
              <TextField
                name='qualifications4InstitutionName'
                value={qualifications4InstitutionName}
                onChange={e => setqualifications4InstitutionName(e.target.value)}
                sx={{ width: '50%' }}
                label='Institution Name 4'
                variant='outlined'
              />
              <TextField
                name='qualifications4YearOfCompletion'
                value={qualifications4YearOfCompletion}
                onChange={e => setqualifications4YearOfCompletion(e.target.value)}
                sx={{ width: '50%' }}
                label='Year of Completion 4'
                variant='outlined'
                // type='number'
              />
            </Box>

            {/* Continue for other qualifications */}
            <TextField
              label='Affiliations'
              fullWidth
              value={affiliations}
              onChange={e => setAffiliations(e.target.value)}
            />
            <TextField
              label='Languages Spoken'
              fullWidth
              value={languagesSpoken}
              onChange={e => setLanguagesSpoken(e.target.value)}
            />
            {/* Additional Fields */}
            <TextField
              label='Areas of Expertise'
              fullWidth
              value={areasOfExpertise}
              onChange={e => setAreasOfExpertise(e.target.value)}
            />
            <TextField
              label='Awards and Recognitions'
              fullWidth
              value={awardsRecognitions}
              onChange={e => setAwardsRecognitions(e.target.value)}
            />
            <TextField
              label='Publications/Research'
              fullWidth
              value={publicationsResearch}
              onChange={e => setPublicationsResearch(e.target.value)}
            />
            <TextField
              label='Social Media Links'
              fullWidth
              value={socialMediaLinks}
              onChange={e => setSocialMediaLinks(e.target.value)}
            />
            <TextField
              label='Personal Bio'
              fullWidth
              multiline
              rows={4}
              value={personalBio}
              onChange={e => setPersonalBio(e.target.value)}
            />
            {/* Categories and Subcategories (if applicable) */}
            <Button type='submit' variant='contained' fullWidth>
              Update Doctor
            </Button>
          </Stack>
        </form>
      </CardContent>
      <Notification open={isOpenNotification} message={notificationMessage} setOpen={setIsOpenNotification} />
    </Card>
  )
}

export default EditDoctorPage
