'use client'

import React, { useEffect, useState } from 'react'
import {
  Button,
  Card,
  HelperText,
  Label,
  Modal,
  ModalBody,
  ModalHeader,
  Select,
  Textarea,
  TextInput,
} from 'flowbite-react'
import Image from 'next/image'
import * as yup from 'yup'
import { toast } from 'react-toastify'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'

import buttonTheme from '@/lib/themes/button'
import { BankAccount as BankAccountType } from '@/lib/types/profile-setting'
import modalTheme from '@/lib/themes/modal'
import { Bank } from '@/lib/types/bank'
import { getBanks } from '@/lib/services/bank-services'
import formTheme from '@/lib/themes/form'
import { handleApiError } from '@/lib/utils/error-handler'
import { requestBankAccountChange } from '@/lib/services/profile-setting-services'

const bankAccountFormSchema = yup.object({
  bank_id: yup.number().required('Bank is required'),
  account_name: yup.string().required('Account name is required'),
  account_number: yup.string().required('Account number is required'),
  reason: yup.string().required('Reason for change is required'),
})

export type BankAccountFormData = yup.InferType<typeof bankAccountFormSchema>

export default function BankAccount(bankAccount: BankAccountType) {
  const [changeAccountModal, setChangeAccountModal] = useState<ModalState>({
    type: 'edit',
    isOpened: false,
  })
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [banks, setBanks] = useState<Bank[]>([])
  const {
    watch,
    register,
    handleSubmit,
    setError,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(bankAccountFormSchema),
    defaultValues: {
      bank_id: undefined,
      account_name: '',
      account_number: '',
      reason: '',
    },
  })

  const formValues = watch()

  useEffect(() => {
    const fetchBanks = async () => {
      try {
        const data = await getBanks()
        setBanks(data)
      } catch {
        toast.error('Failed to load bank list. Please try again later.')
      }
    }

    fetchBanks()
  }, [])

  async function handleChangeAccountSubmit(data: BankAccountFormData) {
    try {
      setIsSubmitting(true)

      await requestBankAccountChange(data)

      toast.success('Bank account change request submitted successfully.')
      setChangeAccountModal({ type: 'edit', isOpened: false })
    } catch (error) {
      handleApiError(
        error,
        'Failed to submit account change request. Please try again later.',
        (formErrors) => {
          Object.keys(formErrors).forEach((field) => {
            setError(field as keyof BankAccountFormData, {
              type: 'server',
              message: formErrors[field][0],
            })
          })
        },
      )
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <React.Fragment>
      <div className="max-w-sm">
        <Card className="shadow-none space-y-10 border border-gray-200 dark:border-gray-700">
          <h2 className="text-xl font-semibold mb-4">
            {bankAccount.bank_name}
          </h2>

          <div className="w-40 h-20 rounded-md mb-4 flex items-center justify-center">
            <Image
              src={bankAccount.bank_logo_url}
              alt={`${bankAccount.bank_name} logo`}
              width={160}
              height={80}
            />
          </div>

          <div className="space-y-1">
            <p className="text-gray-600 dark:text-gray-400 text-sm">
              Account Name
            </p>
            <p className="text-gray-900 dark:text-white font-medium">
              {bankAccount.account_name}
            </p>
          </div>

          <div className="space-y-1">
            <p className="text-gray-600 dark:text-gray-400 text-sm">
              Account Number
            </p>
            <p className="text-gray-900 dark:text-white font-medium">
              {bankAccount.account_number}
            </p>
          </div>

          <Button
            color="blue"
            theme={buttonTheme.button}
            onClick={() =>
              setChangeAccountModal({ type: 'edit', isOpened: true })
            }
          >
            Request Account Change
          </Button>
        </Card>
      </div>

      <Modal
        position="center"
        theme={modalTheme.modal}
        dismissible
        show={changeAccountModal.isOpened && changeAccountModal.type === 'edit'}
        onClose={() => setChangeAccountModal({ type: 'edit', isOpened: false })}
      >
        <ModalHeader>
          <p>Request Bank Account Change</p>
          <p className="text-sm font-normal text-slate-500 mt-2">
            Submit a request to update bank account. Changes will be reviewed
            before approval.
          </p>
        </ModalHeader>

        <ModalBody>
          <form
            onSubmit={handleSubmit(handleChangeAccountSubmit)}
            className="space-y-8"
          >
            {/* Bank Selection */}
            <div>
              <div className="mb-2 block">
                <Label theme={formTheme.label} htmlFor="bank_id">
                  Bank Name <span className="text-red-500">*</span>
                </Label>
              </div>
              <Select
                theme={formTheme.select}
                id="bank_id"
                disabled={banks.length === 0}
                {...register('bank_id')}
              >
                <option value="">-- Select Bank --</option>
                {banks.map((bank) => (
                  <option key={bank.id} value={bank.id}>
                    {bank.bank_name}
                  </option>
                ))}
              </Select>
              <HelperText color="failure">{errors.bank_id?.message}</HelperText>
            </div>

            {/* Account Name */}
            <div>
              <div className="mb-2 block">
                <Label theme={formTheme.label} htmlFor="account_name">
                  Account Name <span className="text-red-500">*</span>
                </Label>
              </div>
              <TextInput
                theme={formTheme.textInput}
                id="account_name"
                type="text"
                placeholder="Enter account name"
                {...register('account_name')}
              />
              <HelperText color="failure">
                {errors.account_name?.message}
              </HelperText>
            </div>

            {/* Account Number */}
            <div>
              <div className="mb-2 block">
                <Label theme={formTheme.label} htmlFor="account_number">
                  Account Number <span className="text-red-500">*</span>
                </Label>
              </div>
              <TextInput
                theme={formTheme.textInput}
                id="account_number"
                type="text"
                placeholder="Enter account number"
                {...register('account_number')}
              />
              <HelperText color="failure">
                {errors.account_number?.message}
              </HelperText>
            </div>

            {/* Reason */}
            <div className="w-full">
              <div className="mb-2 block">
                <Label theme={formTheme.label} htmlFor="reason">
                  Reason for Change <span className="text-red-500">*</span>
                </Label>
              </div>
              <Textarea
                id="reason"
                theme={formTheme.textarea}
                rows={4}
                className="resize-none"
                {...register('reason')}
              >
                {formValues.reason}
              </Textarea>
              <HelperText color="failure">{errors.reason?.message}</HelperText>
            </div>

            <div className="ml-auto w-fit flex items-center gap-2 mt-4">
              <Button
                color="alternative"
                disabled={isSubmitting}
                theme={buttonTheme.button}
                onClick={() =>
                  setChangeAccountModal({ type: 'edit', isOpened: false })
                }
              >
                Cancel
              </Button>
              <Button
                color="blue"
                type="submit"
                theme={buttonTheme.button}
                disabled={isSubmitting}
              >
                Submit Request
              </Button>
            </div>
          </form>
        </ModalBody>
      </Modal>
    </React.Fragment>
  )
}
