'use client'

import { TextField, Typography, useTheme } from '@mui/material'
import { useState } from 'react'
import Loading from '../../../../../../components/layout/shared/Loading'
import { useDashboardAnalytics } from '../../../../../../services/queries/analytics'
import { formatDateDDMMYYYY, formatForInputDate, formatShortCurrency } from '../../../../../../utils/transform'
import OrdersReport from '../../../../../../views/dashboards/orders/OrdersReport'
import PaymentMethodReport from '../../../../../../views/dashboards/payment-methods/PaymentMethodReport'
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'

const DashboardOverview = () => {
  const theme = useTheme()

  const today = new Date()
  const monthAgo = new Date()
  monthAgo.setDate(today.getDate() - 30)

  const [filter, setFilter] = useState({
    date_from: formatDateDDMMYYYY(monthAgo),
    date_to: formatDateDDMMYYYY(today)
  })

  // Sample data - replace with your actual data
  const { data: salesData, isLoading } = useDashboardAnalytics({
    date_from: filter.date_from,
    date_to: filter.date_to
  })

  const MetricCard = ({ iconClass, title, value, subtitle, bgColor = 'bg-blue-500', isCurrency = false }: any) => (
    <div className='bg-white rounded-lg shadow-md hover:shadow-xl transition-shadow duration-300 p-6'>
      <div className='flex items-center justify-between'>
        <div className='flex-1'>
          <h3 className='text-sm font-medium text-gray-600 mb-2'>{title}</h3>
          <p className='text-2xl font-bold text-gray-900 mb-1'>{isCurrency ? 'Rp ' + value : value}</p>
          {subtitle && <p className='text-sm text-gray-500'>{subtitle}</p>}
        </div>
        <div className={`px-4 py-3 rounded-full ${bgColor} bg-opacity-10`}>
          <i className={`${iconClass} text-[32px] ${bgColor.replace('bg-', 'text-')}`}></i>
        </div>
      </div>
    </div>
  )

  return (
    <>
      <div>
        {/* Header */}
        <div className='mb-8 flex gap-4 items-center justify-between'>
          <Typography variant='h1' className='text-3xl font-bold text-gray-900 mb-2'>
            Analysis Dashboard
          </Typography>
          <div className='flex items-center gap-4'>
            <TextField
              type='date'
              value={formatForInputDate(salesData?.date_from || new Date())}
              onChange={e => {
                setFilter({
                  ...filter,
                  date_from: formatDateDDMMYYYY(new Date(e.target.value))
                })
              }}
              size='small'
              sx={{
                '& .MuiOutlinedInput-root': {
                  '&.Mui-focused fieldset': {
                    borderColor: 'primary.main'
                  },
                  '& fieldset': {
                    borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
                  }
                }
              }}
            />
            <Typography>-</Typography>
            <TextField
              type='date'
              value={
                salesData?.date_to
                  ? new Date(salesData?.date_to).toISOString().split('T')[0]
                  : new Date().toISOString().split('T')[0]
              }
              onChange={e => {}}
              size='small'
              sx={{
                '& .MuiOutlinedInput-root': {
                  '&.Mui-focused fieldset': {
                    borderColor: 'primary.main'
                  },
                  '& fieldset': {
                    borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
                  }
                }
              }}
            />
          </div>
        </div>

        {salesData ? (
          <>
            {/* Overview Metrics */}
            <div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8'>
              <MetricCard
                iconClass='tabler-shopping-cart'
                title='Total Orders'
                value={salesData.overview.total_orders.toLocaleString()}
                subtitle={`${salesData.overview.voided_orders} voided, ${salesData.overview.refunded_orders} refunded`}
                bgColor='bg-blue-500'
              />
              <MetricCard
                iconClass='tabler-cash'
                title='Total Sales'
                value={formatShortCurrency(salesData.overview.total_sales)}
                bgColor='bg-green-500'
                isCurrency={true}
              />
              <MetricCard
                iconClass='tabler-trending-up'
                title='Average Order Value'
                value={formatShortCurrency(salesData.overview.average_order_value)}
                bgColor='bg-purple-500'
                isCurrency={true}
              />
              <MetricCard
                iconClass='tabler-users'
                title='Total Customers'
                value={salesData.overview.total_customers || 'N/A'}
                bgColor='bg-orange-500'
              />
            </div>

            <div className='grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8'>
              {/* Top Products */}
              <ProductSales title='Top Products' productData={salesData.top_products} />

              {/* Payment Methods */}
              <PaymentMethodReport payments={salesData.payment_methods} />
            </div>

            {/* Recent Sales */}
            <OrdersReport title='Recent Sales' orderData={salesData.recent_sales} />
          </>
        ) : (
          <Loading />
        )}
      </div>
    </>
  )
}

export default DashboardOverview
