'use client'

// React Imports
import { useState } from 'react'

// Next Imports
import dynamic from 'next/dynamic'

// MUI Imports
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import Button from '@mui/material/Button'
import ButtonGroup from '@mui/material/ButtonGroup'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import TableFooter from '@mui/material/TableFooter'
import Typography from '@mui/material/Typography'

// Third Party Imports
import type { ApexOptions } from 'apexcharts'

// Components Imports
import OptionMenu from '@core/components/option-menu'

// Styled Component Imports
const AppReactApexCharts = dynamic(() => import('@/libs/styles/AppReactApexCharts'))

// Data
const productData = [
  { kategori: 'Dress', jumlah: 174, nilai: 70629279 },
  { kategori: 'Tshirt', jumlah: 163, nilai: 31667892 },
  { kategori: 'Shoes', jumlah: 27, nilai: 13473000 },
  { kategori: 'Misc', jumlah: 128, nilai: 123937 }
]

const totalJumlah = productData.reduce((sum, item) => sum + item.jumlah, 0)
const totalNilai = productData.reduce((sum, item) => sum + item.nilai, 0)

// Chart series and colors
const series = productData.map(item => item.nilai)
const colors = ['#FF6B9D', '#FFD93D', '#6BCF7F', '#4D96FF']

const PurchaseProductSalesChart = () => {
  const [activeView, setActiveView] = useState<'chart' | 'table'>('chart')

  const options: ApexOptions = {
    chart: {
      type: 'donut'
    },
    labels: productData.map(item => item.kategori),
    colors: colors,
    legend: {
      position: 'bottom',
      horizontalAlign: 'center',
      fontSize: '14px',
      markers: {
        width: 12,
        height: 12,
        radius: 2
      },
      itemMargin: {
        horizontal: 15,
        vertical: 5
      }
    },
    plotOptions: {
      pie: {
        donut: {
          size: '70%'
        }
      }
    },
    dataLabels: {
      enabled: false
    },
    tooltip: {
      y: {
        formatter: function (val) {
          return 'Rp ' + val.toLocaleString('id-ID')
        }
      }
    },
    stroke: {
      width: 2,
      colors: ['#fff']
    }
  }

  const formatCurrency = (amount: number): string => {
    return amount.toLocaleString('id-ID')
  }

  return (
    <Card className='mt-5'>
      <CardHeader
        title='Total Pembelian Bulan Ini'
        action={
          <div className='flex items-center gap-2'>
            <div className='w-4 h-4 bg-gray-300 rounded cursor-pointer'></div>
            <OptionMenu options={['View More', 'Delete']} />
          </div>
        }
      />
      <CardContent>
        {/* Toggle Buttons */}
        <div className='flex justify-center mb-6'>
          <ButtonGroup size='small'>
            <Button
              variant={activeView === 'chart' ? 'contained' : 'outlined'}
              onClick={() => setActiveView('chart')}
              sx={{
                minWidth: '120px',
                backgroundColor: activeView === 'chart' ? '#36175e' : 'transparent',
                color: activeView === 'chart' ? 'white' : '#36175e',
                borderColor: '#36175e',
                '&:hover': {
                  backgroundColor: activeView === 'chart' ? '#36175e' : 'rgba(25, 118, 210, 0.04)'
                }
              }}
            >
              Jenis Produk
            </Button>
            <Button
              variant={activeView === 'table' ? 'contained' : 'outlined'}
              onClick={() => setActiveView('table')}
              sx={{
                minWidth: '120px',
                backgroundColor: activeView === 'table' ? '#36175e' : 'transparent',
                color: activeView === 'table' ? 'white' : '#36175e',
                borderColor: '#36175e',
                '&:hover': {
                  backgroundColor: activeView === 'table' ? '#36175e' : 'rgba(25, 118, 210, 0.04)'
                }
              }}
            >
              Kategori
            </Button>
          </ButtonGroup>
        </div>

        {/* Content based on active view */}
        {activeView === 'chart' ? (
          // Donut Chart View (Slide 1)
          <div className='flex flex-col items-center'>
            <AppReactApexCharts
              id='product-sales-donut'
              type='donut'
              height={350}
              width='100%'
              series={series}
              options={options}
            />
          </div>
        ) : (
          // Table View (Slide 2)
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 600 }}>Kategori</TableCell>
                  <TableCell align='center' sx={{ fontWeight: 600 }}>
                    Jml
                  </TableCell>
                  <TableCell align='right' sx={{ fontWeight: 600 }}>
                    Nilai
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {productData.map((row, index) => (
                  <TableRow key={index}>
                    <TableCell>{row.kategori}</TableCell>
                    <TableCell align='center'>{row.jumlah}</TableCell>
                    <TableCell align='right'>{formatCurrency(row.nilai)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
              <TableFooter>
                <TableRow sx={{ backgroundColor: '#f5f5f5' }}>
                  <TableCell sx={{ fontWeight: 700, fontSize: '14px' }}>Total</TableCell>
                  <TableCell align='center' sx={{ fontWeight: 700, fontSize: '14px' }}>
                    {totalJumlah}
                  </TableCell>
                  <TableCell align='right' sx={{ fontWeight: 700, fontSize: '14px' }}>
                    {formatCurrency(totalNilai)}
                  </TableCell>
                </TableRow>
              </TableFooter>
            </Table>
          </TableContainer>
        )}

        {/* Two dot indicators at bottom */}
        <div className='flex justify-center items-center gap-2 mt-6'>
          <div
            className={`w-3 h-3 rounded-full cursor-pointer transition-colors ${
              activeView === 'chart' ? 'bg-primary' : 'bg-gray-300'
            }`}
            onClick={() => setActiveView('chart')}
          ></div>
          <div
            className={`w-3 h-3 rounded-full cursor-pointer transition-colors ${
              activeView === 'table' ? 'bg-primary' : 'bg-gray-300'
            }`}
            onClick={() => setActiveView('table')}
          ></div>
        </div>
      </CardContent>
    </Card>
  )
}

export default PurchaseProductSalesChart
