'use client'

import React, { useState } from 'react'
import {
  Button,
  HelperText,
  Label,
  TextInput,
  Alert,
  Card,
} from 'flowbite-react'
import * as yup from 'yup'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'

import formTheme from '@/lib/themes/form'
import buttonTheme from '@/lib/themes/button'
import { handleApiError } from '@/lib/utils/error-handler'
import { updateAccountInfo } from '@/lib/services/profile-setting-services'

const formSchema = yup.object({
  email: yup
    .string()
    .trim()
    .email('Invalid email address')
    .required('Email address is required'),
})

export type AccountInfoFormValues = yup.InferType<typeof formSchema>

export interface AccountInfoFormProps {
  email: string
}

export default function AccountInfoForm({ email }: AccountInfoFormProps) {
  const [processing, setProcessing] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)

  const {
    handleSubmit,
    register,
    formState: { errors },
    setError: setFieldError,
  } = useForm({
    resolver: yupResolver(formSchema),
    defaultValues: {
      email: email || '',
    },
  })

  async function handleUpdateAccountInfo(
    data: yup.InferType<typeof formSchema>,
  ) {
    try {
      setProcessing(true)
      setError(null)
      setSuccess(null)

      await updateAccountInfo(data)

      setSuccess('Account information updated successfully.')
    } catch (err) {
      handleApiError(err, 'An unexpected error occurred.', (formErrors) => {
        Object.keys(formErrors).forEach((field) => {
          setFieldError(field as keyof AccountInfoFormValues, {
            type: 'server',
            message: formErrors[field][0],
          })
        })
      })
    } finally {
      setProcessing(false)
    }
  }

  return (
    <div className="max-w-md">
      <Card className="shadow-none border border-gray-200">
        <div>
          <h2 className="text-lg font-semibold text-slate-900 dark:text-white">
            Account Information
          </h2>
          <p className="text-slate-500 dark:text-slate-400 mb-6">
            Update your account information below.
          </p>
        </div>

        {error && (
          <Alert
            color="failure"
            className="mb-4"
            onDismiss={() => {
              setError(null)
            }}
          >
            {error}
          </Alert>
        )}

        {success && (
          <Alert
            color="success"
            className="mb-4"
            onDismiss={() => {
              setSuccess(null)
            }}
          >
            {success}
          </Alert>
        )}

        <form
          onSubmit={handleSubmit(handleUpdateAccountInfo)}
          className="space-y-4"
        >
          <div>
            <div className="mb-2">
              <Label htmlFor="email">Email Address</Label>
            </div>
            <TextInput
              id="email"
              type="text"
              placeholder="Enter your email address..."
              color={errors.email ? 'failure' : 'gray'}
              theme={formTheme.textInput}
              disabled={processing}
              {...register('email')}
            />
            {errors.email && (
              <HelperText color="failure">{errors.email.message}</HelperText>
            )}
          </div>

          <div className="pt-4">
            <Button
              type="submit"
              disabled={processing}
              theme={buttonTheme.button}
              className="w-full"
            >
              {processing ? 'Updating...' : 'Update'}
            </Button>
          </div>
        </form>
      </Card>
    </div>
  )
}
