'use client'

import {
  Box,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  Grid2 as Grid,
  IconButton,
  Stack,
  Tooltip,
  Typography
} from '@mui/material'
import type { Theme } from '@mui/material/styles'

import Button from '@/@core/components/mui/Button'
import CustomTextField from '@/@core/components/mui/TextField'
import { formatDate } from '@/utils'
import type { IPaymentLink } from '@/types'
import type { PaymentLinkStatus } from '@/hooks/data/payment-link'

type Translate = (key: string, values?: Record<string, any>) => string

type PaymentLinksDialogsProps = {
  t: Translate
  theme: Theme
  locale: string
  statusLabelMap: Record<PaymentLinkStatus, string>
  statusColorMap: Record<PaymentLinkStatus, 'default' | 'warning' | 'success' | 'error'>
  handleCopy: (value?: string | null) => void
  createOpen: boolean
  setCreateOpen: (open: boolean) => void
  createValues: {
    amount: string
    customer_name: string
    customer_email: string
    customer_phone: string
    description: string
    expires_at: string
  }
  setCreateValues: (
    updater: (prev: PaymentLinksDialogsProps['createValues']) => PaymentLinksDialogsProps['createValues']
  ) => void
  createErrors: Record<string, string>
  isCreating: boolean
  onCreateSubmit: () => void
  editOpen: boolean
  setEditOpen: (open: boolean) => void
  editValues: { customer_name: string; description: string }
  setEditValues: (
    updater: (prev: { customer_name: string; description: string }) => { customer_name: string; description: string }
  ) => void
  isUpdating: boolean
  onUpdateSubmit: () => void
  viewOpen: boolean
  setViewOpen: (open: boolean) => void
  activeLink: IPaymentLink | null
  cancelOpen: boolean
  setCancelOpen: (open: boolean) => void
  isCancelling: boolean
  onCancelSubmit: () => void
  deleteOpen: boolean
  setDeleteOpen: (open: boolean) => void
  isDeleting: boolean
  onDeleteSubmit: () => void
  createdDialogOpen: boolean
  setCreatedDialogOpen: (open: boolean) => void
  createdLinkUrl: string | null
}

const PaymentLinksDialogs = ({
  t,
  theme,
  locale,
  statusLabelMap,
  statusColorMap,
  handleCopy,
  createOpen,
  setCreateOpen,
  createValues,
  setCreateValues,
  createErrors,
  isCreating,
  onCreateSubmit,
  editOpen,
  setEditOpen,
  editValues,
  setEditValues,
  isUpdating,
  onUpdateSubmit,
  viewOpen,
  setViewOpen,
  activeLink,
  cancelOpen,
  setCancelOpen,
  isCancelling,
  onCancelSubmit,
  deleteOpen,
  setDeleteOpen,
  isDeleting,
  onDeleteSubmit,
  createdDialogOpen,
  setCreatedDialogOpen,
  createdLinkUrl
}: PaymentLinksDialogsProps) => {
  return (
    <>
      <Dialog open={createOpen} onClose={() => setCreateOpen(false)} fullWidth maxWidth='sm'>
        <DialogTitle>{t('dialogs.createTitle')}</DialogTitle>
        <DialogContent className='space-y-4'>
          <Grid container spacing={3}>
            <Grid size={{ xs: 12, md: 6 }}>
              <CustomTextField
                fullWidth
                label={t('fields.amount')}
                type='number'
                value={createValues.amount}
                onChange={event => setCreateValues(prev => ({ ...prev, amount: event.target.value }))}
                error={Boolean(createErrors.amount)}
                helperText={createErrors.amount}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <CustomTextField
                fullWidth
                label={t('fields.expiresAt')}
                type='date'
                value={createValues.expires_at}
                onChange={event => setCreateValues(prev => ({ ...prev, expires_at: event.target.value }))}
                slotProps={{ inputLabel: { shrink: true } }}
                error={Boolean(createErrors.expires_at)}
                helperText={createErrors.expires_at}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <CustomTextField
                fullWidth
                label={t('fields.customerName')}
                value={createValues.customer_name}
                onChange={event => setCreateValues(prev => ({ ...prev, customer_name: event.target.value }))}
                error={Boolean(createErrors.customer_name)}
                helperText={createErrors.customer_name}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <CustomTextField
                fullWidth
                label={t('fields.customerEmail')}
                type='email'
                value={createValues.customer_email}
                onChange={event => setCreateValues(prev => ({ ...prev, customer_email: event.target.value }))}
                error={Boolean(createErrors.customer_email)}
                helperText={createErrors.customer_email}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <CustomTextField
                fullWidth
                label={t('fields.customerPhone')}
                value={createValues.customer_phone}
                inputProps={{ inputMode: 'tel', pattern: '^\\+?\\d{7,15}$', dir: 'ltr' }}
                onChange={event => {
                  const rawValue = event.target.value
                  const cleaned = rawValue.replace(/[^+\d]/g, '')
                  const normalized = cleaned.startsWith('+')
                    ? `+${cleaned.replace(/\+/g, '').replace(/\D/g, '')}`
                    : cleaned.replace(/\D/g, '')

                  setCreateValues(prev => ({ ...prev, customer_phone: normalized }))
                }}
                error={Boolean(createErrors.customer_phone)}
                helperText={createErrors.customer_phone}
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <CustomTextField
                fullWidth
                label={t('fields.description')}
                value={createValues.description}
                onChange={event => setCreateValues(prev => ({ ...prev, description: event.target.value }))}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button variant='outlined' color='warning' onClick={() => setCreateOpen(false)} disabled={isCreating}>
            {t('actions.cancel')}
          </Button>
          <Button variant='contained' onClick={onCreateSubmit} disabled={isCreating} isLoading={isCreating}>
            {t('actions.createShort')}
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={editOpen} onClose={() => setEditOpen(false)} fullWidth maxWidth='sm'>
        <DialogTitle>{t('dialogs.editTitle')}</DialogTitle>
        <DialogContent className='space-y-4'>
          <CustomTextField
            fullWidth
            label={t('fields.customerName')}
            value={editValues.customer_name}
            onChange={event => setEditValues(prev => ({ ...prev, customer_name: event.target.value }))}
          />
          <CustomTextField
            fullWidth
            label={t('fields.description')}
            value={editValues.description}
            onChange={event => setEditValues(prev => ({ ...prev, description: event.target.value }))}
          />
        </DialogContent>
        <DialogActions>
          <Button variant='outlined' color='error' onClick={() => setEditOpen(false)} disabled={isUpdating}>
            {t('actions.cancel')}
          </Button>
          <Button variant='contained' onClick={onUpdateSubmit} disabled={isUpdating} isLoading={isUpdating}>
            {t('actions.save')}
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={viewOpen} onClose={() => setViewOpen(false)} fullWidth maxWidth='sm'>
        <DialogTitle>{t('dialogs.viewTitle')}</DialogTitle>
        <DialogContent>
          {activeLink ? (
            <Stack spacing={3}>
              <Box
                sx={{
                  borderRadius: 2,
                  backgroundColor: theme.palette.action.hover,
                  p: 2
                }}
              >
                <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} justifyContent='space-between'>
                  <Box>
                    <Typography variant='caption' color='text.secondary'>
                      {t('details.uuid')}
                    </Typography>
                    <Typography fontWeight={600}>{activeLink.uuid}</Typography>
                  </Box>
                  <Stack direction='row' spacing={1} alignItems='center'>
                    <Chip
                      size='small'
                      label={statusLabelMap[activeLink.payment_status]}
                      color={statusColorMap[activeLink.payment_status]}
                    />
                    <Typography fontWeight={600}>
                      {activeLink.amount} {activeLink.currency}
                    </Typography>
                  </Stack>
                </Stack>
              </Box>

              <Grid container spacing={3}>
                <Grid size={{ xs: 12, md: 6 }}>
                  <Typography variant='caption' color='text.secondary'>
                    {t('details.customer')}
                  </Typography>
                  <Typography>{activeLink.customer_name || '--'}</Typography>
                  <Typography variant='body2' color='text.secondary'>
                    {activeLink.customer_email || '--'}
                  </Typography>
                </Grid>
                <Grid size={{ xs: 12, md: 6 }}>
                  <Typography variant='caption' color='text.secondary'>
                    {t('details.description')}
                  </Typography>
                  <Typography>{activeLink.description || '--'}</Typography>
                </Grid>
              </Grid>

              <Divider />

              <Grid container spacing={3}>
                <Grid size={{ xs: 12, md: 4 }}>
                  <Typography variant='caption' color='text.secondary'>
                    {t('details.created')}
                  </Typography>
                  <Typography>{formatDate(activeLink.created_at, locale)}</Typography>
                </Grid>
                <Grid size={{ xs: 12, md: 4 }}>
                  <Typography variant='caption' color='text.secondary'>
                    {t('details.expires')}
                  </Typography>
                  <Typography>{formatDate(activeLink.expires_at, locale)}</Typography>
                </Grid>
                <Grid size={{ xs: 12, md: 4 }}>
                  <Typography variant='caption' color='text.secondary'>
                    {t('details.paid')}
                  </Typography>
                  <Typography>{formatDate(activeLink.paid_at, locale)}</Typography>
                </Grid>
              </Grid>

              <Box>
                <Typography variant='caption' color='text.secondary'>
                  {t('details.publicUrl')}
                </Typography>
                {activeLink.public_url ? (
                  <Stack direction='row' spacing={1} alignItems='center' flexWrap='wrap'>
                    <Typography className='break-all'>{activeLink.public_url}</Typography>
                    <Tooltip title={t('actions.copy')}>
                      <IconButton size='small' color='primary' onClick={() => handleCopy(activeLink.public_url)}>
                        <i className='tabler-copy' />
                      </IconButton>
                    </Tooltip>
                    <Tooltip title={t('actions.open')}>
                      <IconButton
                        size='small'
                        color='primary'
                        component='a'
                        href={activeLink.public_url}
                        target='_blank'
                        rel='noopener noreferrer'
                      >
                        <i className='tabler-external-link' />
                      </IconButton>
                    </Tooltip>
                  </Stack>
                ) : (
                  <Typography>--</Typography>
                )}
              </Box>
            </Stack>
          ) : (
            <Typography color='text.secondary'>{t('dialogs.noSelection')}</Typography>
          )}
        </DialogContent>
        <DialogActions>
          <Button variant='outlined' onClick={() => setViewOpen(false)}>
            {t('actions.close')}
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={cancelOpen} onClose={() => setCancelOpen(false)} fullWidth maxWidth='xs'>
        <DialogTitle>{t('dialogs.cancelTitle')}</DialogTitle>
        <DialogContent>
          <Typography variant='body2' color='text.secondary'>
            {t('dialogs.cancelText')}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button variant='outlined' color='error' onClick={() => setCancelOpen(false)} disabled={isCancelling}>
            {t('actions.cancel')}
          </Button>
          <Button
            variant='contained'
            color='warning'
            onClick={onCancelSubmit}
            disabled={isCancelling}
            isLoading={isCancelling}
          >
            {t('actions.cancelLink')}
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={deleteOpen} onClose={() => setDeleteOpen(false)} fullWidth maxWidth='xs'>
        <DialogTitle>{t('dialogs.deleteTitle')}</DialogTitle>
        <DialogContent>
          <Typography variant='body2' color='text.secondary'>
            {t('dialogs.deleteText')}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button variant='outlined' color='warning' onClick={() => setDeleteOpen(false)} disabled={isDeleting}>
            {t('actions.cancel')}
          </Button>
          <Button
            variant='contained'
            color='error'
            onClick={onDeleteSubmit}
            disabled={isDeleting}
            isLoading={isDeleting}
          >
            {t('actions.delete')}
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={createdDialogOpen} onClose={() => setCreatedDialogOpen(false)} fullWidth maxWidth='xs'>
        <DialogTitle>{t('dialogs.createdTitle')}</DialogTitle>
        <DialogContent className='space-y-4'>
          <Typography variant='body2' color='text.secondary'>
            {t('dialogs.createdText')}
          </Typography>
          <Box
            sx={{
              borderRadius: 2,
              border: `1px solid ${theme.palette.divider}`,
              backgroundColor: theme.palette.action.hover,
              p: 2
            }}
          >
            <Stack spacing={1.5}>
              <Typography variant='caption' color='text.secondary'>
                {t('details.publicUrl')}
              </Typography>
              <Typography className='break-all'>{createdLinkUrl || '--'}</Typography>
              <Stack direction='row' spacing={1}>
                <Button
                  variant='outlined'
                  onClick={() => handleCopy(createdLinkUrl)}
                  disabled={!createdLinkUrl}
                  startIcon={<i className='tabler-copy' />}
                >
                  {t('actions.copy')}
                </Button>
                <Button
                  variant='contained'
                  onClick={() => {
                    if (createdLinkUrl) window.open(createdLinkUrl, '_blank', 'noopener,noreferrer')
                  }}
                  disabled={!createdLinkUrl}
                  startIcon={<i className='tabler-external-link' />}
                >
                  {t('actions.open')}
                </Button>
              </Stack>
            </Stack>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button variant='outlined' onClick={() => setCreatedDialogOpen(false)}>
            {t('actions.close')}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default PaymentLinksDialogs
