'use client'

import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { toast } from 'react-toastify'
import { Button, HelperText, Label, TextInput } from 'flowbite-react'

import formTheme from '@/lib/themes/form'
import buttonTheme from '@/lib/themes/button'
import * as withdrawalSettingServices from '@/lib/services/withdrawal-setting-services'
import { handleApiError } from '@/lib/utils/error-handler'
import {
  withdrawalSettingFormSchema,
  WithdrawalSettingFormValues,
} from '../schema'

export default function MainContent() {
  const [isLoading, setIsLoading] = useState(true)
  const [isProcessing, setIsProcessing] = useState(false)

  const form = useForm<WithdrawalSettingFormValues>({
    resolver: yupResolver(withdrawalSettingFormSchema),
    defaultValues: {
      min_withdrawal_amount: '0',
      max_withdrawal_amount: '0',
      withdrawal_daily_limit: 0,
      withdrawal_fee: '0',
    },
  })

  async function handleSubmitForm(formValues: WithdrawalSettingFormValues) {
    setIsProcessing(true)

    try {
      const updatedSetting =
        await withdrawalSettingServices.updateWithdrawalSetting(formValues)

      form.reset(updatedSetting)

      toast.success('Withdrawal settings updated successfully!')
    } catch (err) {
      handleApiError(
        err,
        'Oops! Something went wrong. Please try again later.',
        (formErrors) => {
          Object.keys(formErrors).forEach((field) => {
            form.setError(field as keyof WithdrawalSettingFormValues, {
              type: 'manual',
              message: formErrors[field][0],
            })
          })
        },
      )
    } finally {
      setIsProcessing(false)
    }
  }

  useEffect(() => {
    setIsLoading(true)

    withdrawalSettingServices
      .getWithdrawalSetting()
      .then((setting) => {
        form.reset(setting)
      })
      .catch(() => {
        toast.error('Failed to load withdrawal settings. Please try again.')
      })
      .finally(() => {
        setIsLoading(false)
      })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <section className="mt-8">
      <div>
        <h1 className="text-3xl font-semibold text-black mb-2">
          Withdrawal Settings
        </h1>
        <p className="font-medium text-slate-500">
          Configure the withdrawal limits and fee applied to partner withdrawal
          requests.
        </p>
      </div>

      {isLoading ? (
        <p className="text-slate-500 mt-8">Loading withdrawal settings...</p>
      ) : (
        <form
          onSubmit={form.handleSubmit(handleSubmitForm)}
          className="mt-8 max-w-xl space-y-6"
        >
          <div>
            <div className="mb-2 block">
              <Label htmlFor="min_withdrawal_amount" theme={formTheme.label}>
                Minimum Withdrawal Amount (IDR)
              </Label>
            </div>
            <TextInput
              id="min_withdrawal_amount"
              type="text"
              placeholder="0"
              theme={formTheme.textInput}
              disabled={isProcessing}
              {...form.register('min_withdrawal_amount')}
            />
            <HelperText color="failure">
              {form.formState.errors.min_withdrawal_amount?.message}
            </HelperText>
          </div>

          <div>
            <div className="mb-2 block">
              <Label htmlFor="max_withdrawal_amount" theme={formTheme.label}>
                Maximum Withdrawal Amount (IDR)
              </Label>
            </div>
            <TextInput
              id="max_withdrawal_amount"
              type="text"
              placeholder="0"
              theme={formTheme.textInput}
              disabled={isProcessing}
              {...form.register('max_withdrawal_amount')}
            />
            <HelperText color="failure">
              {form.formState.errors.max_withdrawal_amount?.message}
            </HelperText>
          </div>

          <div>
            <div className="mb-2 block">
              <Label htmlFor="withdrawal_daily_limit" theme={formTheme.label}>
                Withdrawal Daily Limit
              </Label>
            </div>
            <TextInput
              id="withdrawal_daily_limit"
              type="number"
              placeholder="0"
              theme={formTheme.textInput}
              disabled={isProcessing}
              {...form.register('withdrawal_daily_limit')}
            />
            <HelperText color="failure">
              {form.formState.errors.withdrawal_daily_limit?.message}
            </HelperText>
          </div>

          <div>
            <div className="mb-2 block">
              <Label htmlFor="withdrawal_fee" theme={formTheme.label}>
                Withdrawal Fee (IDR)
              </Label>
            </div>
            <TextInput
              id="withdrawal_fee"
              type="text"
              placeholder="0"
              theme={formTheme.textInput}
              disabled={isProcessing}
              {...form.register('withdrawal_fee')}
            />
            <HelperText color="failure">
              {form.formState.errors.withdrawal_fee?.message}
            </HelperText>
          </div>

          <div>
            <Button
              type="submit"
              theme={buttonTheme.button}
              disabled={isProcessing}
            >
              {isProcessing ? 'Saving...' : 'Save Settings'}
            </Button>
          </div>
        </form>
      )}
    </section>
  )
}
