'use client'

import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import Stack from '@mui/material/Stack'
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import Alert from '@mui/material/Alert'
import Paper from '@mui/material/Paper'
import Tooltip from '@mui/material/Tooltip'
import CircularProgress from '@mui/material/CircularProgress'

import CustomTextField from '@core/components/mui/TextField'
import type { OrderItemInput } from '@/@core/hooks/data/orders'
import type { IOrder } from '@/types/data'

interface OrderItemsDrawerProps {
  open: boolean
  onClose: () => void
  order: IOrder | null
  onSubmit: (items: OrderItemInput[]) => void
  loading: boolean
}

const OrderItemsDrawer = ({ open, onClose, order, onSubmit, loading }: OrderItemsDrawerProps) => {
  const t = useTranslations('ORDERS')
  const [localItems, setLocalItems] = useState<(OrderItemInput & { name: string })[]>([])

  useEffect(() => {
    if (open && order?.items) {
      setLocalItems(
        order?.items
          .filter(item => Boolean(item.product_id))
          .map(item => ({
            product_id: item.product_id as string,
            quantity: item.quantity,
            selected_variations: (item.selected_variations || [])
              .map(variation => (typeof variation === 'string' ? variation : variation?.id))
              .filter(Boolean) as string[],
            special_instructions: item.special_instructions || '',
            name: item.product_name_en
          }))
      )
    }
  }, [open, order])

  const handleItemChange = (index: number, key: 'quantity' | 'special_instructions', value: string) => {
    setLocalItems(items =>
      items.map((item, i) =>
        i === index
          ? {
              ...item,
              [key]: key === 'quantity' ? Number(value) || 1 : value
            }
          : item
      )
    )
  }

  const handleRemoveItem = (index: number) => {
    setLocalItems(items => items.filter((_, i) => i !== index))
  }

  const canSubmit = localItems.length > 0 && localItems.every(item => item.product_id && item.quantity > 0)

  return (
    <Drawer anchor='right' open={open} onClose={onClose}>
      <Box sx={{ width: 420, display: 'flex', flexDirection: 'column', height: '100%' }}>
        <Box sx={{ p: 3, borderBottom: 1, borderColor: 'divider', bgcolor: 'primary.main', color: 'white' }}>
          <Stack direction='row' alignItems='center' justifyContent='space-between'>
            <Stack direction='row' spacing={2} alignItems='center'>
              <Box
                sx={{
                  width: 40,
                  height: 40,
                  borderRadius: 2,
                  bgcolor: 'rgba(255, 255, 255, 0.2)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              >
                <i className='tabler-shopping-cart text-xl' />
              </Box>
              <Typography variant='h6' fontWeight={600}>
                {t('itemsDrawer.title')}
              </Typography>
            </Stack>
            <IconButton size='small' onClick={onClose} sx={{ color: 'white' }}>
              <i className='tabler-x' />
            </IconButton>
          </Stack>
        </Box>
        <Box sx={{ flex: 1, overflow: 'auto', p: 3 }}>
          {localItems.length === 0 ? (
            <Alert severity='info' icon={<i className='tabler-info-circle' />}>
              {t('itemsDrawer.empty')}
            </Alert>
          ) : (
            <Stack spacing={2}>
              {localItems.map((item, index) => (
                <Paper
                  key={`${item.product_id}-${index}`}
                  elevation={0}
                  sx={{ p: 2, border: 1, borderColor: 'divider', borderRadius: 2 }}
                >
                  <Stack spacing={2}>
                    <Stack direction='row' alignItems='center' justifyContent='space-between'>
                      <Typography fontWeight={600}>{item.name}</Typography>
                      <Tooltip title={t('itemsDrawer.remove')}>
                        <IconButton size='small' onClick={() => handleRemoveItem(index)} color='error'>
                          <i className='tabler-trash' />
                        </IconButton>
                      </Tooltip>
                    </Stack>
                    <Stack spacing={2} direction='row'>
                      <CustomTextField
                        type='number'
                        label={t('itemsDrawer.quantity')}
                        value={item.quantity}
                        onChange={e => handleItemChange(index, 'quantity', e.target.value)}
                        sx={{ width: 100 }}
                        inputProps={{ min: 1 }}
                        size='small'
                      />
                      <CustomTextField
                        label={t('itemsDrawer.instructions')}
                        value={item.special_instructions || ''}
                        onChange={e => handleItemChange(index, 'special_instructions', e.target.value)}
                        fullWidth
                        size='small'
                      />
                    </Stack>
                  </Stack>
                </Paper>
              ))}
            </Stack>
          )}
        </Box>
        <Box sx={{ p: 3, borderTop: 1, borderColor: 'divider', bgcolor: 'background.paper' }}>
          <Stack direction='row' spacing={2} justifyContent='flex-end'>
            <Button onClick={onClose} variant='outlined'>
              {t('cancel')}
            </Button>
            <Button
              variant='contained'
              onClick={() => onSubmit(localItems)}
              disabled={!canSubmit || loading}
              startIcon={
                loading ? <CircularProgress size={16} color='inherit' /> : <i className='tabler-device-floppy' />
              }
            >
              {t('save')}
            </Button>
          </Stack>
        </Box>
      </Box>
    </Drawer>
  )
}

export default OrderItemsDrawer
