'use client'
import React, { useState } from 'react'
import { Card, CardContent, CardHeader, Typography, Button, Box, Stack } from '@mui/material'
import IngedientUnitConversionDrawer from './IngedientUnitConversionDrawer' // Sesuaikan dengan path file Anda
import { Ingredient } from '@/types/services/productRecipe'
import { useUnitConverterByIngredient } from '@/services/queries/unitConverter'

interface Props {
  data: Ingredient | undefined
}

const IngredientDetailUnit = ({ data }: Props) => {
  // State untuk mengontrol drawer
  const [openConversionDrawer, setOpenConversionDrawer] = useState(false)

  const { data: unitConverters, isLoading } = useUnitConverterByIngredient(data?.id as string)

  // Function untuk membuka drawer
  const handleOpenConversionDrawer = () => {
    setOpenConversionDrawer(true)
  }

  // Function untuk menutup drawer
  const handleCloseConversionDrawer = () => {
    setOpenConversionDrawer(false)
  }

  // Function untuk handle data dari drawer (opsional)
  const handleSetConversionData = (data: any) => {
    console.log('Conversion data received:', data)
    // Anda bisa menambahkan logic untuk mengupdate state atau API call di sini
  }

  return (
    <>
      <Card sx={{ maxWidth: 400 }}>
        <CardHeader title='Satuan' />
        <CardContent>
          <Stack spacing={2} sx={{ mb: 3 }}>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Typography variant='body1' color='text.secondary'>
                Satuan Dasar
              </Typography>
              <Typography variant='body1' sx={{ fontWeight: 'medium' }}>
                : {data?.unit.name ?? '-'}
              </Typography>
            </Box>
            {unitConverters?.map(unitConverter => (
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <Typography variant='body1' color='text.secondary'>
                  1 {unitConverter.from_unit.name}
                </Typography>
                <Typography variant='body1' sx={{ fontWeight: 'medium' }}>
                  : {unitConverter.conversion_factor} {unitConverter.to_unit.name}
                </Typography>
              </Box>
            )) ?? []}
          </Stack>

          <Button
            variant='contained'
            fullWidth
            startIcon={<span style={{ fontSize: '18px' }}>+</span>}
            onClick={handleOpenConversionDrawer}
            sx={{
              py: 1.5,
              borderRadius: 2,
              textTransform: 'none',
              fontSize: '16px'
            }}
          >
            Ubah konversi satuan
          </Button>
        </CardContent>
      </Card>

      {/* Ingredient Unit Conversion Drawer */}
      <IngedientUnitConversionDrawer
        open={openConversionDrawer}
        handleClose={handleCloseConversionDrawer}
        setData={handleSetConversionData}
        data={data}
      />
    </>
  )
}

export default IngredientDetailUnit
