'use client'

import { useEffect, useMemo, useState } from 'react'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import Button from '@mui/material/Button'
import Grid from '@mui/material/Grid2'
import Switch from '@mui/material/Switch'
import FormControlLabel from '@mui/material/FormControlLabel'
import CircularProgress from '@mui/material/CircularProgress'
import Stack from '@mui/material/Stack'
import MenuItem from '@mui/material/MenuItem'
import Alert from '@mui/material/Alert'
import { Controller, useForm, useWatch } from 'react-hook-form'
import { useTranslations } from 'next-intl'
import { toast } from 'react-toastify'

import CustomTextField from '@core/components/mui/TextField'
import {
  ICreatePaymentMethodPayload,
  IUpdatePaymentMethodPayload,
  IPaymentMethodDetails
} from '@/types/data/payment-method'
import {
  useCreatePaymentMethod,
  useUpdatePaymentMethod,
  useGetPaymentMethodDetails
} from '@/@core/hooks/data/payment-methods'

type PaymentMethodFormMode = 'create' | 'edit'

type Props = {
  open: boolean
  mode: PaymentMethodFormMode
  methodId?: string | null
  onClose: () => void
  onSuccess?: () => void
}

const defaultValues: ICreatePaymentMethodPayload = {
  code: '',
  name_en: '',
  name_ar: '',
  description_en: '',
  description_ar: '',
  instructions_en: '',
  instructions_ar: '',
  type: 'offline',
  requires_online_payment: false,
  sort_order: 1,
  is_active: true,
  fee_percentage: '',
  fee_fixed: '',
  bank_name: '',
  account_number: '',
  account_holder: '',
  iban: '',
  swift_code: '',
  wallet_number: '',
  wallet_holder: '',
  gateway_url: '',
  gateway_config: []
}

const PaymentMethodFormDrawer = ({ open, mode, methodId, onClose, onSuccess }: Props) => {
  const t = useTranslations('paymentMethods.form')
  const rootT = useTranslations('paymentMethods')
  const messageT = useTranslations('paymentMethods.messages')
  const [formError, setFormError] = useState<string | null>(null)

  const createMutation = useCreatePaymentMethod()
  const updateMutation = useUpdatePaymentMethod()

  const { control, handleSubmit, reset } = useForm<ICreatePaymentMethodPayload>({
    defaultValues
  })
  const typeValue = useWatch({ control, name: 'type', defaultValue: 'offline' })
  const isOnline = typeValue === 'online'

  const { data: methodResponse, isFetching: isLoadingDetails } = useGetPaymentMethodDetails(methodId || undefined, {
    enabled: mode === 'edit' && Boolean(methodId)
  })

  const editingMethod: IPaymentMethodDetails | undefined = methodResponse?.data

  const isSubmitting = createMutation.isPending || updateMutation.isPending
  const handleClose = () => {
    if (!isSubmitting) {
      setFormError(null)
      onClose()
    }
  }

  useEffect(() => {
    if (!open) {
      return
    }

    if (mode === 'edit' && editingMethod) {
      reset({
        code: editingMethod.code || '',
        name_en: editingMethod.name_en || '',
        name_ar: editingMethod.name_ar || '',
        description_en: editingMethod.description_en || '',
        description_ar: editingMethod.description_ar || '',
        instructions_en: editingMethod.instructions_en || '',
        instructions_ar: editingMethod.instructions_ar || '',
        type: editingMethod.type || 'offline',
        requires_online_payment: editingMethod.requires_online_payment ?? false,
        sort_order: editingMethod.sort_order ?? 1,
        is_active: editingMethod.is_active ?? true,
        fee_percentage: editingMethod.fee_percentage ?? '',
        fee_fixed: editingMethod.fee_fixed ?? '',
        bank_name: editingMethod.bank_name || '',
        account_number: editingMethod.account_number || '',
        account_holder: editingMethod.account_holder || '',
        iban: editingMethod.iban || '',
        swift_code: editingMethod.swift_code || '',
        wallet_number: editingMethod.wallet_number || '',
        wallet_holder: editingMethod.wallet_holder || '',
        gateway_url: editingMethod.gateway_url || '',
        gateway_config: editingMethod.gateway_config || []
      })
    } else if (mode === 'create') {
      reset(defaultValues)
    }
    setFormError(null)
  }, [open, mode, editingMethod, reset])

  const drawerTitle = mode === 'create' ? t('createTitle') : t('editTitle')
  const drawerSubtitle = mode === 'create' ? t('createSubtitle') : t('editSubtitle')

  const submitLabel = useMemo(() => {
    if (isSubmitting) {
      return t('saving')
    }

    return t('submit')
  }, [isSubmitting, t])

  const formatPayload = (values: ICreatePaymentMethodPayload): ICreatePaymentMethodPayload => ({
    ...values,
    code: values.code.trim(),
    name_en: values.name_en.trim(),
    name_ar: values.name_ar.trim(),
    description_en: values.description_en?.trim() || '',
    description_ar: values.description_ar?.trim() || '',
    instructions_en: values.instructions_en?.trim() || '',
    instructions_ar: values.instructions_ar?.trim() || '',
    fee_percentage: values.fee_percentage === '' ? '' : String(values.fee_percentage),
    fee_fixed: values.fee_fixed === '' ? '' : String(values.fee_fixed),
    sort_order: Number(values.sort_order) || 1,
    bank_name: values.bank_name?.trim() || '',
    account_number: values.account_number?.trim() || '',
    account_holder: values.account_holder?.trim() || '',
    iban: values.iban?.trim() || '',
    swift_code: values.swift_code?.trim() || '',
    wallet_number: values.wallet_number?.trim() || '',
    wallet_holder: values.wallet_holder?.trim() || '',
    gateway_url: values.gateway_url?.trim() || '',
    gateway_config: values.gateway_config || []
  })

  const onSubmit = async (values: ICreatePaymentMethodPayload) => {
    const payload = formatPayload(values)
    setFormError(null)

    try {
      if (mode === 'create') {
        const response = await createMutation.mutateAsync(payload)
        toast.success(response?.messages || messageT('created'))
      } else if (mode === 'edit' && methodId) {
        const updatePayload: IUpdatePaymentMethodPayload = {
          ...payload
        }
        const response = await updateMutation.mutateAsync({ paymentMethodId: methodId, payload: updatePayload })
        toast.success(response?.messages || messageT('updated'))
      }
      onSuccess?.()
      onClose()
    } catch (error) {
      console.error('Failed to submit payment method form', error)
      const apiMessage = (error as any)?.response?.data?.message
      const friendlyMessage = apiMessage || messageT('error')
      setFormError(friendlyMessage)
      toast.error(friendlyMessage)
    }
  }

  const labelWithAsterisk = (label: string, required?: boolean) => (required ? `${label} *` : label)

  const renderSectionTitle = (title: string, subtitle?: string) => (
    <Stack spacing={0.5}>
      <Typography variant='subtitle1' fontWeight={600}>
        {title}
      </Typography>
      {subtitle && (
        <Typography variant='body2' color='text.secondary'>
          {subtitle}
        </Typography>
      )}
    </Stack>
  )

  const renderForm = () => {
    if (mode === 'edit' && isLoadingDetails && !editingMethod) {
      return (
        <div className='flex items-center justify-center py-10'>
          <CircularProgress />
        </div>
      )
    }

    return (
      <form onSubmit={handleSubmit(onSubmit)} className='flex flex-col gap-4'>
        {renderSectionTitle(t('basicInfoTitle'))}
        <Grid container spacing={3}>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='code'
              control={control}
              rules={{ required: true }}
              render={({ field }) => (
                <CustomTextField {...field} label={labelWithAsterisk(t('code'), true)} fullWidth />
              )}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='type'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} select label={labelWithAsterisk(t('type'), true)} fullWidth>
                  <MenuItem value='offline'>{rootT('types.offline')}</MenuItem>
                  <MenuItem value='online'>{rootT('types.online')}</MenuItem>
                </CustomTextField>
              )}
            />
          </Grid>
        </Grid>

        <Grid container spacing={3}>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='name_en'
              control={control}
              rules={{ required: true }}
              render={({ field }) => (
                <CustomTextField {...field} label={labelWithAsterisk(t('nameEn'), true)} fullWidth />
              )}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='name_ar'
              control={control}
              rules={{ required: true }}
              render={({ field }) => (
                <CustomTextField {...field} label={labelWithAsterisk(t('nameAr'), true)} fullWidth />
              )}
            />
          </Grid>
        </Grid>

        <Grid container spacing={3}>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='description_en'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} label={t('descriptionEn')} multiline minRows={2} fullWidth />
              )}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='description_ar'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} label={t('descriptionAr')} multiline minRows={2} fullWidth />
              )}
            />
          </Grid>
        </Grid>

        <Grid container spacing={3}>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='instructions_en'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} label={t('instructionsEn')} multiline minRows={3} fullWidth />
              )}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <Controller
              name='instructions_ar'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} label={t('instructionsAr')} multiline minRows={3} fullWidth />
              )}
            />
          </Grid>
        </Grid>

        <Grid container spacing={3}>
          <Grid size={{ xs: 12, sm: 4 }}>
            <Controller
              name='fee_percentage'
              control={control}
              render={({ field }) => (
                <CustomTextField
                  {...field}
                  type='number'
                  label={labelWithAsterisk(t('feePercentage'), true)}
                  fullWidth
                />
              )}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 4 }}>
            <Controller
              name='fee_fixed'
              control={control}
              render={({ field }) => <CustomTextField {...field} type='number' label={t('feeFixed')} fullWidth />}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 4 }}>
            <Controller
              name='sort_order'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} type='number' label={t('sortOrder')} inputProps={{ min: 1 }} fullWidth />
              )}
            />
          </Grid>
        </Grid>

        <Grid container spacing={3}>
          <Grid size={{ xs: 12 }}>
            <Controller
              name='gateway_url'
              control={control}
              render={({ field }) => (
                <CustomTextField {...field} label={t('gatewayUrl')} fullWidth disabled={!isOnline} />
              )}
            />
          </Grid>
        </Grid>

        <Controller
          name='gateway_config'
          control={control}
          render={({ field }) => {
            const value = Array.isArray(field.value) ? field.value.join('\n') : field.value || ''

            return (
              <CustomTextField
                {...field}
                value={value}
                onChange={event => {
                  const lines = event.target.value
                    .split('\n')
                    .map(line => line.trim())
                    .filter(Boolean)

                  field.onChange(lines)
                }}
                label={t('gatewayConfig')}
                helperText={t('gatewayConfigHelper')}
                multiline
                minRows={3}
                fullWidth
                disabled={!isOnline}
              />
            )
          }}
        />

        {isOnline ? (
          <>
            {renderSectionTitle(t('bankSection'))}
            <Grid container spacing={3}>
              <Grid size={{ xs: 12, sm: 6 }}>
                <Controller
                  name='bank_name'
                  control={control}
                  render={({ field }) => (
                    <CustomTextField {...field} label={t('bankName')} fullWidth disabled={!isOnline} />
                  )}
                />
              </Grid>
              <Grid size={{ xs: 12, sm: 6 }}>
                <Controller
                  name='account_holder'
                  control={control}
                  render={({ field }) => (
                    <CustomTextField {...field} label={t('accountHolder')} fullWidth disabled={!isOnline} />
                  )}
                />
              </Grid>
              <Grid size={{ xs: 12, sm: 6 }}>
                <Controller
                  name='account_number'
                  control={control}
                  render={({ field }) => (
                    <CustomTextField {...field} label={t('accountNumber')} fullWidth disabled={!isOnline} />
                  )}
                />
              </Grid>
              <Grid size={{ xs: 12, sm: 6 }}>
                <Controller
                  name='iban'
                  control={control}
                  render={({ field }) => (
                    <CustomTextField {...field} label={t('iban')} fullWidth disabled={!isOnline} />
                  )}
                />
              </Grid>
              <Grid size={{ xs: 12, sm: 6 }}>
                <Controller
                  name='swift_code'
                  control={control}
                  render={({ field }) => (
                    <CustomTextField {...field} label={t('swift')} fullWidth disabled={!isOnline} />
                  )}
                />
              </Grid>
            </Grid>

            {renderSectionTitle(t('walletSection'), t('walletHint'))}
            <Grid container spacing={3}>
              <Grid size={{ xs: 12, sm: 6 }}>
                <Controller
                  name='wallet_holder'
                  control={control}
                  render={({ field }) => (
                    <CustomTextField {...field} label={t('walletHolder')} fullWidth disabled={!isOnline} />
                  )}
                />
              </Grid>
              <Grid size={{ xs: 12, sm: 6 }}>
                <Controller
                  name='wallet_number'
                  control={control}
                  render={({ field }) => (
                    <CustomTextField {...field} label={t('walletNumber')} fullWidth disabled={!isOnline} />
                  )}
                />
              </Grid>
            </Grid>
          </>
        ) : (
          <Typography variant='body2' color='text.secondary'>
            {t('offlineHint')}
          </Typography>
        )}

        <Stack spacing={1}>
          <Controller
            name='requires_online_payment'
            control={control}
            render={({ field }) => (
              <FormControlLabel
                control={
                  <Switch
                    {...field}
                    checked={Boolean(field.value)}
                    onChange={(_, checked) => field.onChange(checked)}
                  />
                }
                label={t('requiresOnline')}
              />
            )}
          />
          <Typography variant='caption' color='text.secondary'>
            {t('requiresOnlineHint')}
          </Typography>
        </Stack>

        <Controller
          name='is_active'
          control={control}
          render={({ field }) => (
            <FormControlLabel
              control={
                <Switch {...field} checked={Boolean(field.value)} onChange={(_, checked) => field.onChange(checked)} />
              }
              label={field.value ? t('isActive') : rootT('status.inactive')}
            />
          )}
        />

        <Stack direction='row' justifyContent='flex-end' spacing={2} pt={2}>
          <Button variant='tonal' color='secondary' onClick={onClose} disabled={isSubmitting}>
            {t('cancel')}
          </Button>
          <Button type='submit' variant='contained' disabled={isSubmitting}>
            {isSubmitting ? <CircularProgress size={18} color='inherit' /> : submitLabel}
          </Button>
        </Stack>
      </form>
    )
  }

  return (
    <Dialog open={open} onClose={handleClose} fullWidth maxWidth='md'>
      <DialogTitle>
        <Stack direction='row' alignItems='center' justifyContent='space-between'>
          <div>
            <Typography variant='h6'>{drawerTitle}</Typography>
            <Typography variant='body2' color='text.secondary'>
              {drawerSubtitle}
            </Typography>
          </div>
          <IconButton onClick={handleClose} disabled={isSubmitting}>
            <i className='tabler-x text-textSecondary' />
          </IconButton>
        </Stack>
      </DialogTitle>
      <DialogContent dividers>
        <Divider sx={{ mb: 4 }} />
        {renderForm()}
      </DialogContent>
    </Dialog>
  )
}

export default PaymentMethodFormDrawer
