'use client'

import React, { useState } from 'react'
import {
  Card,
  CardContent,
  Typography,
  Button,
  Box,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Tooltip,
  IconButton,
  CardHeader
} from '@mui/material'
import Grid from '@mui/material/Grid2'
import CustomTextField from '@/@core/components/mui/TextField'
import ImageUpload from '@/components/ImageUpload'
import { useFilesMutation } from '@/services/mutations/files'
import { usePurchaseOrdersMutation } from '@/services/mutations/purchaseOrder'

// API Interface
export interface SendPaymentPurchaseOrderRequest {
  reference?: string
  status?: 'received'
  attachment_file_ids?: string[] // uuid.UUID[]
}

interface PaymentFormData {
  totalDibayar: string
  referensi: string
  nomor: string
}

interface PurchaseDetailSendPaymentProps {
  id?: string
  totalAmount?: number
  purchaseOrderNumber?: string
  onSubmit?: (data: SendPaymentPurchaseOrderRequest) => Promise<void>
  loading?: boolean
}

const PurchaseDetailSendPayment: React.FC<PurchaseDetailSendPaymentProps> = ({
  id,
  totalAmount = 849000,
  purchaseOrderNumber = 'PP/00025',
  onSubmit,
  loading = false
}) => {
  const [formData, setFormData] = useState<PaymentFormData>({
    totalDibayar: totalAmount.toString(),
    referensi: '',
    nomor: purchaseOrderNumber
  })

  const [expanded, setExpanded] = useState<boolean>(false)
  const [uploadedFileIds, setUploadedFileIds] = useState<string[]>([])
  const [imageUrl, setImageUrl] = useState<string>('')
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false)

  const { mutate, isPending } = useFilesMutation().uploadFile
  const { sendPaymentPurchaseOrder } = usePurchaseOrdersMutation()

  const handleChange =
    (field: keyof PaymentFormData) => (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
      setFormData(prev => ({
        ...prev,
        [field]: event.target.value
      }))
    }

  const handleAccordionChange = () => {
    setExpanded(!expanded)
  }

  const formatCurrency = (amount: string | number): string => {
    const numAmount = typeof amount === 'string' ? parseInt(amount.replace(/\D/g, '')) : amount
    return new Intl.NumberFormat('id-ID').format(numAmount)
  }

  const upsertAttachment = (attachments: string[], newId: string, index = 0) => {
    if (attachments.length === 0) {
      return [newId]
    }
    return attachments.map((id, i) => (i === index ? newId : id))
  }

  const handleUpload = async (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('file_type', 'image')
      formData.append('description', 'image purchase order payment')

      mutate(formData, {
        onSuccess: r => {
          setUploadedFileIds(prev => upsertAttachment(prev, r.id))
          setImageUrl(r.file_url)
          resolve(r.id)
        },
        onError: er => {
          reject(er)
        }
      })
    })
  }

  const handleSubmit = async () => {
    setIsSubmitting(true)

    try {
      const requestData: SendPaymentPurchaseOrderRequest = {
        reference: formData.referensi || undefined,
        status: 'received',
        attachment_file_ids: uploadedFileIds.length > 0 ? uploadedFileIds : undefined
      }
      sendPaymentPurchaseOrder.mutate(
        {
          id: id as string,
          payload: requestData
        },
        {
          onSuccess: () => {
            // Reset form after successful submission
            setFormData(prev => ({
              ...prev,
              referensi: ''
            }))
            setUploadedFileIds([])
            setExpanded(false)
          }
        }
      )
    } catch (error) {
      console.error('Error submitting payment:', error)
      // Handle error (you might want to show a toast or error message)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Card>
      <CardHeader
        title={
          <Box display='flex' justifyContent='space-between' alignItems='center'>
            <Typography variant='h5' color='error' sx={{ fontWeight: 'bold' }}>
              Kirim Pembayaran
            </Typography>
          </Box>
        }
      />
      <CardContent>
        <Grid container spacing={3}>
          {/* Left Column */}
          <Grid size={{ xs: 12, md: 6 }}>
            {/* Total Dibayar - DISABLED */}
            <Box sx={{ mb: 3 }}>
              <CustomTextField
                fullWidth
                label={
                  <span>
                    <span style={{ color: 'red' }}>*</span> Total Dibayar
                  </span>
                }
                value={formData.totalDibayar}
                onChange={handleChange('totalDibayar')}
                disabled
                sx={{
                  '& .MuiInputBase-root': {
                    textAlign: 'right'
                  }
                }}
              />
            </Box>

            {/* Referensi */}
            <Box sx={{ mb: 3 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                <Typography variant='body2' sx={{ color: 'text.secondary' }}>
                  Referensi
                </Typography>
                <Tooltip title='Informasi referensi pembayaran'>
                  <IconButton size='small' sx={{ ml: 0.5 }}>
                    <i className='tabler-info-circle' style={{ fontSize: '16px', color: '#666' }} />
                  </IconButton>
                </Tooltip>
              </Box>
              <CustomTextField
                fullWidth
                placeholder='Referensi'
                value={formData.referensi}
                onChange={handleChange('referensi')}
                disabled={loading || isSubmitting}
              />
            </Box>

            {/* Attachment Accordion */}
            <Accordion
              expanded={expanded}
              onChange={handleAccordionChange}
              disabled={loading || isSubmitting}
              sx={{
                boxShadow: 'none',
                border: '1px solid #e0e0e0',
                borderRadius: '8px',
                '&:before': { display: 'none' }
              }}
            >
              <AccordionSummary
                expandIcon={
                  <i
                    className='tabler-chevron-right'
                    style={{
                      transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)',
                      transition: 'transform 0.2s'
                    }}
                  />
                }
                sx={{
                  backgroundColor: '#f8f9fa',
                  borderRadius: '8px',
                  minHeight: '48px',
                  '& .MuiAccordionSummary-content': {
                    margin: '12px 0'
                  }
                }}
              >
                <Typography variant='body2' sx={{ fontWeight: 'medium' }}>
                  Attachment {uploadedFileIds.length > 0 && `(${uploadedFileIds.length})`}
                </Typography>
              </AccordionSummary>
              <AccordionDetails sx={{ p: 2 }}>
                <ImageUpload
                  onUpload={handleUpload}
                  maxFileSize={1 * 1024 * 1024} // 1MB
                  currentImageUrl={imageUrl}
                  dragDropText='Drop your image here'
                  browseButtonText='Choose Image'
                />
              </AccordionDetails>
            </Accordion>
          </Grid>

          {/* Right Column */}
          <Grid size={{ xs: 12, md: 6 }}>
            {/* Nomor - DISABLED */}
            <Box sx={{ mb: 3 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                <Typography variant='body2' sx={{ color: 'text.secondary' }}>
                  Nomor
                </Typography>
                <Tooltip title='Nomor pembayaran otomatis'>
                  <IconButton size='small' sx={{ ml: 0.5 }}>
                    <i className='tabler-info-circle' style={{ fontSize: '16px', color: '#666' }} />
                  </IconButton>
                </Tooltip>
              </Box>
              <CustomTextField fullWidth value={formData.nomor} onChange={handleChange('nomor')} disabled />
            </Box>
          </Grid>
        </Grid>

        {/* Bottom Section */}
        <Box sx={{ mt: 4, pt: 3, borderTop: '1px solid #e0e0e0' }}>
          <Grid container spacing={2} alignItems='center'>
            <Grid size={{ xs: 12, md: 6 }}>{/* Empty space */}</Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                <Typography variant='h6' sx={{ fontWeight: 'bold' }}>
                  Total
                </Typography>
                <Typography variant='h6' sx={{ fontWeight: 'bold' }}>
                  {formatCurrency(formData.totalDibayar)}
                </Typography>
              </Box>

              <Button
                variant='contained'
                startIcon={<i className='tabler-plus' />}
                fullWidth
                onClick={handleSubmit}
                disabled={loading || isSubmitting}
                sx={{
                  py: 1.5,
                  textTransform: 'none',
                  fontWeight: 'medium'
                }}
              >
                {isSubmitting ? 'Mengirim...' : 'Tambah Pembayaran'}
              </Button>
            </Grid>
          </Grid>
        </Box>
      </CardContent>
    </Card>
  )
}

export default PurchaseDetailSendPayment
