'use client'

import React, { useState } from 'react'
import { Button, HelperText, Label, TextInput, Alert } 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 {
  updateProfile,
  UpdateProfileFormValues,
} from '@/lib/services/merchant-services'
import { useMerchant } from '@/lib/context/MerchantContext'
import { handleApiError } from '@/lib/utils/error-handler'

const formSchema = yup.object({
  name: yup.string().required('Merchant name is required'),
  username: yup
    .string()
    .trim()
    .matches(
      /^[a-z0-9_]+$/,
      'Username can only contain letters, numbers, and underscores',
    )
    .min(3, 'Username must be at least 3 characters')
    .required('Username is required'),
})

export default function BasicInfoForm() {
  const { merchant, loading: loadingMerchant } = useMerchant()
  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: {
      name: merchant?.name || '',
      username: merchant?.username || '',
    },
  })

  async function handleUpdateProfile(data: yup.InferType<typeof formSchema>) {
    if (!merchant) return

    try {
      setProcessing(true)
      setError(null)
      setSuccess(null)

      await updateProfile(merchant.id, data)

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

  if (loadingMerchant) {
    return (
      <div className="text-center py-8">
        <p className="text-gray-500 dark:text-gray-400">
          Loading merchant information...
        </p>
      </div>
    )
  }

  return (
    <div className="max-w-md">
      <div>
        <h2 className="text-lg font-semibold text-slate-900 dark:text-white">
          Basic Information
        </h2>
        <p className="text-slate-500 dark:text-slate-400 mb-6">
          Update merchant basic 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(handleUpdateProfile)} className="space-y-4">
        <div>
          <div className="mb-2">
            <Label htmlFor="name">Merchant Name</Label>
          </div>
          <TextInput
            id="name"
            type="text"
            placeholder="Enter merchant name..."
            color={errors.name ? 'failure' : 'gray'}
            theme={formTheme.textInput}
            disabled={processing}
            {...register('name')}
          />
          {errors.name && (
            <HelperText color="failure">{errors.name.message}</HelperText>
          )}
        </div>

        <div>
          <div className="mb-2">
            <Label htmlFor="username">Username</Label>
          </div>
          <TextInput
            id="username"
            type="text"
            placeholder="Enter merchant username..."
            color={errors.username ? 'failure' : 'gray'}
            theme={formTheme.textInput}
            disabled={processing}
            {...register('username')}
          />
          {errors.username && (
            <HelperText color="failure">{errors.username.message}</HelperText>
          )}
        </div>

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