'use client'

import React, { useState, useEffect } from 'react'
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  LineChart,
  Line
} from 'recharts'
import { useProductSalesAnalytics } from '../../../../../../../services/queries/analytics'
import Loading from '../../../../../../../components/layout/shared/Loading'
import { formatDateDDMMYYYY } from '../../../../../../../utils/transform'
import PickerBasic from '../../../../../../../components/date-picker/PickerBasic'

// Tabler icons component
const TablerIcon = ({ name = '', className = '' }) => <i className={`tabler-${name} ${className}`} />

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

  const [dateFrom, setDateFrom] = useState<Date | null>(monthAgo)
  const [dateTo, setDateTo] = useState<Date | null>(today)
  const [selectedCategory, setSelectedCategory] = useState('all')
  const [sortBy, setSortBy] = useState('revenue')
  const [sortOrder, setSortOrder] = useState('desc')

  const { data: analytics, isLoading } = useProductSalesAnalytics({
    date_from: formatDateDDMMYYYY(dateFrom!),
    date_to: formatDateDDMMYYYY(dateTo!)
  })

  useEffect(() => {
    if (analytics) {
      setDateFrom(new Date(analytics.date_from))
      setDateTo(new Date(analytics.date_to))
    }
  }, [analytics])

  // Format currency
  const formatCurrency = (amount: any) => {
    return new Intl.NumberFormat('id-ID', {
      style: 'currency',
      currency: 'IDR',
      minimumFractionDigits: 0
    }).format(amount)
  }

  // Calculate summary metrics
  const summary = {
    totalProducts: analytics?.data.length,
    totalQuantitySold: analytics?.data.reduce((sum, item) => sum + item.quantity_sold, 0),
    totalRevenue: analytics?.data.reduce((sum, item) => sum + item.revenue, 0),
    totalOrders: analytics?.data.reduce((sum, item) => sum + item.order_count, 0),
    averageOrderValue: analytics?.data
      ? analytics!.data.reduce((sum, item) => sum + item.revenue, 0) /
        analytics!.data.reduce((sum, item) => sum + item.order_count, 0)
      : 0
  }

  // Get unique categories
  const categories = ['all', ...new Set(analytics?.data.map(item => item.category_name))]

  // Filter and sort data
  const filteredData = analytics?.data
    .filter(item => selectedCategory === 'all' || item.category_name === selectedCategory)
    .sort((a: any, b: any) => {
      const multiplier = sortOrder === 'desc' ? -1 : 1
      return (a[sortBy] - b[sortBy]) * multiplier
    })

  // Prepare chart data
  const chartData = filteredData?.slice(0, 10).map(item => ({
    name: item.product_name.length > 15 ? item.product_name.substring(0, 15) + '...' : item.product_name,
    fullName: item.product_name,
    revenue: item.revenue,
    quantity: item.quantity_sold,
    orders: item.order_count,
    avgPrice: item.average_price
  }))

  // Category performance data
  const categoryData = categories
    .filter(cat => cat !== 'all')
    .map(category => {
      const categoryItems = analytics?.data.filter(item => item.category_name === category)
      return {
        name: category,
        revenue: categoryItems?.reduce((sum, item) => sum + item.revenue, 0),
        quantity: categoryItems?.reduce((sum, item) => sum + item.quantity_sold, 0),
        products: categoryItems?.length
      }
    })

  // Colors for charts
  const colors = ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#06B6D4', '#84CC16', '#F97316']

  // Metric cards data
  const metrics = [
    {
      title: 'Total Revenue',
      value: formatCurrency(summary.totalRevenue),
      icon: 'currency-dollar',
      color: 'text-green-600',
      bgColor: 'bg-green-50',
      subtitle: 'From all products'
    },
    {
      title: 'Products Sold',
      value: summary.totalQuantitySold?.toLocaleString(),
      icon: 'package',
      color: 'text-blue-600',
      bgColor: 'bg-blue-50',
      subtitle: `${summary.totalProducts} different products`
    },
    {
      title: 'Total Orders',
      value: summary.totalOrders?.toLocaleString(),
      icon: 'shopping-cart',
      color: 'text-purple-600',
      bgColor: 'bg-purple-50',
      subtitle: 'Completed orders'
    },
    {
      title: 'Avg Order Value',
      value: formatCurrency(summary.averageOrderValue || 0),
      icon: 'trending-up',
      color: 'text-orange-600',
      bgColor: 'bg-orange-50',
      subtitle: 'Per order average'
    }
  ]

  const handleSort = (field: any) => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'desc' ? 'asc' : 'desc')
    } else {
      setSortBy(field)
      setSortOrder('desc')
    }
  }

  if (isLoading) return <Loading />

  return (
    <div className='mx-auto space-y-6'>
      {/* Header */}
      <div className='flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 mb-8 bg-white shadow p-6 rounded-xl'>
        <div>
          <h1 className='text-4xl font-bold text-gray-800 mb-2'>Product Analytics</h1>
        </div>

        {/* Filters */}
        <div className='flex flex-col sm:flex-row gap-4'>
          <PickerBasic dateFrom={dateFrom} dateTo={dateTo} onChangeDateFrom={setDateFrom} onChangeDateTo={setDateTo} />
        </div>
      </div>

      {/* Summary Cards */}
      <div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6'>
        {metrics.map((metric, index) => (
          <div
            key={index}
            className='bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 border border-gray-100'
          >
            <div className='p-6'>
              <div className='flex items-start justify-between'>
                <div className='flex-1'>
                  <p className='text-gray-500 text-sm font-medium mb-2'>{metric.title}</p>
                  <h3 className='text-2xl font-bold text-gray-800 mb-1'>{metric.value}</h3>
                  <p className='text-gray-500 text-xs'>{metric.subtitle}</p>
                </div>
                <div className={`p-4 rounded-xl ${metric.bgColor}`}>
                  <TablerIcon name={metric.icon} className={`text-2xl ${metric.color}`} />
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Charts Section */}
      <div className='grid grid-cols-1 xl:grid-cols-3 gap-6'>
        {/* Product Revenue Chart */}
        <div className='xl:col-span-2 bg-white rounded-xl shadow-lg border border-gray-100'>
          <div className='p-6'>
            <div className='flex items-center gap-3 mb-6'>
              <TablerIcon name='chart-bar' className='text-blue-600 text-2xl' />
              <h2 className='text-xl font-semibold text-gray-800'>Top Products by Revenue</h2>
            </div>
            <div className='h-80'>
              <ResponsiveContainer width='100%' height='100%'>
                <BarChart data={chartData} margin={{ top: 20, right: 30, left: 20, bottom: 60 }}>
                  <CartesianGrid strokeDasharray='3 3' stroke='#f0f0f0' />
                  <XAxis dataKey='name' stroke='#6b7280' angle={-45} textAnchor='end' height={100} fontSize={12} />
                  <YAxis tickFormatter={value => `${(value / 1000).toFixed(0)}K`} stroke='#6b7280' />
                  <Tooltip
                    formatter={(value, name) => [
                      name === 'revenue' ? formatCurrency(value) : value.toLocaleString(),
                      name === 'revenue' ? 'Revenue' : name === 'quantity' ? 'Quantity Sold' : 'Orders'
                    ]}
                    labelFormatter={label => {
                      const item = chartData?.find(d => d.name === label)
                      return item ? item.fullName : label
                    }}
                    contentStyle={{
                      backgroundColor: '#fff',
                      border: '1px solid #e5e7eb',
                      borderRadius: '8px',
                      boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)'
                    }}
                  />
                  <Bar dataKey='revenue' fill='#3B82F6' radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>

        {/* Category Distribution */}
        <div className='bg-white rounded-xl shadow-lg border border-gray-100'>
          <div className='p-6'>
            <div className='flex items-center gap-3 mb-6'>
              <TablerIcon name='chart-pie' className='text-purple-600 text-2xl' />
              <h2 className='text-xl font-semibold text-gray-800'>Category Distribution</h2>
            </div>
            <div className='h-80'>
              <ResponsiveContainer width='100%' height='100%'>
                <PieChart>
                  <Pie
                    data={categoryData}
                    cx='50%'
                    cy='50%'
                    outerRadius={80}
                    dataKey='revenue'
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  >
                    {categoryData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={colors[index % colors.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={value => [formatCurrency(value), 'Revenue']}
                    contentStyle={{
                      backgroundColor: '#fff',
                      border: '1px solid #e5e7eb',
                      borderRadius: '8px',
                      boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)'
                    }}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>
      </div>

      {/* Quantity vs Orders Chart */}
      <div className='bg-white rounded-xl shadow-lg border border-gray-100'>
        <div className='p-6'>
          <div className='flex items-center gap-3 mb-6'>
            <TablerIcon name='chart-line' className='text-green-600 text-2xl' />
            <h2 className='text-xl font-semibold text-gray-800'>Quantity Sold vs Order Count</h2>
          </div>
          <div className='h-80'>
            <ResponsiveContainer width='100%' height='100%'>
              <BarChart data={chartData}>
                <CartesianGrid strokeDasharray='3 3' stroke='#f0f0f0' />
                <XAxis dataKey='name' stroke='#6b7280' angle={-45} textAnchor='end' height={100} fontSize={12} />
                <YAxis stroke='#6b7280' />
                <Tooltip
                  labelFormatter={label => {
                    const item = chartData?.find(d => d.name === label)
                    return item ? item.fullName : label
                  }}
                  contentStyle={{
                    backgroundColor: '#fff',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px',
                    boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)'
                  }}
                />
                <Bar dataKey='quantity' fill='#10B981' name='Quantity Sold' radius={[4, 4, 0, 0]} />
                <Bar dataKey='orders' fill='#F59E0B' name='Order Count' radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Detailed Products Table */}
      <div className='bg-white rounded-xl shadow-lg border border-gray-100'>
        <div className='p-6'>
          <div className='flex items-center justify-between mb-6'>
            <div className='flex items-center gap-3'>
              <TablerIcon name='table' className='text-indigo-600 text-2xl' />
              <h2 className='text-xl font-semibold text-gray-800'>Product Performance Details</h2>
            </div>
            <div className='text-sm text-gray-500'>Showing {filteredData?.length} products</div>
          </div>

          <div className='overflow-x-auto'>
            <table className='w-full'>
              <thead>
                <tr className='bg-gray-50 border-b border-gray-200'>
                  <th className='text-left py-4 px-6 font-semibold text-gray-700'>Product</th>
                  <th className='text-left py-4 px-6 font-semibold text-gray-700'>Category</th>
                  <th
                    className='text-right py-4 px-6 font-semibold text-gray-700 cursor-pointer hover:text-blue-600 transition-colors'
                    onClick={() => handleSort('quantity_sold')}
                  >
                    <div className='flex items-center justify-end gap-1'>
                      Quantity Sold
                      <TablerIcon
                        name={sortBy === 'quantity_sold' && sortOrder === 'desc' ? 'chevron-down' : 'chevron-up'}
                        className='text-xs'
                      />
                    </div>
                  </th>
                  <th
                    className='text-right py-4 px-6 font-semibold text-gray-700 cursor-pointer hover:text-blue-600 transition-colors'
                    onClick={() => handleSort('revenue')}
                  >
                    <div className='flex items-center justify-end gap-1'>
                      Revenue
                      <TablerIcon
                        name={sortBy === 'revenue' && sortOrder === 'desc' ? 'chevron-down' : 'chevron-up'}
                        className='text-xs'
                      />
                    </div>
                  </th>
                  <th
                    className='text-right py-4 px-6 font-semibold text-gray-700 cursor-pointer hover:text-blue-600 transition-colors'
                    onClick={() => handleSort('average_price')}
                  >
                    <div className='flex items-center justify-end gap-1'>
                      Avg Price
                      <TablerIcon
                        name={sortBy === 'average_price' && sortOrder === 'desc' ? 'chevron-down' : 'chevron-up'}
                        className='text-xs'
                      />
                    </div>
                  </th>
                  <th
                    className='text-right py-4 px-6 font-semibold text-gray-700 cursor-pointer hover:text-blue-600 transition-colors'
                    onClick={() => handleSort('order_count')}
                  >
                    <div className='flex items-center justify-end gap-1'>
                      Orders
                      <TablerIcon
                        name={sortBy === 'order_count' && sortOrder === 'desc' ? 'chevron-down' : 'chevron-up'}
                        className='text-xs'
                      />
                    </div>
                  </th>
                </tr>
              </thead>
              <tbody>
                {filteredData?.map((product, index) => (
                  <tr key={product.product_id} className='border-b border-gray-100 hover:bg-gray-50 transition-colors'>
                    <td className='py-4 px-6'>
                      <div className='font-medium text-gray-800'>{product.product_name}</div>
                    </td>
                    <td className='py-4 px-6'>
                      <span className='inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800'>
                        {product.category_name}
                      </span>
                    </td>
                    <td className='py-4 px-6 text-right font-semibold text-gray-800'>
                      {product.quantity_sold.toLocaleString()}
                    </td>
                    <td className='py-4 px-6 text-right font-semibold text-green-600'>
                      {formatCurrency(product.revenue)}
                    </td>
                    <td className='py-4 px-6 text-right text-gray-700'>{formatCurrency(product.average_price)}</td>
                    <td className='py-4 px-6 text-right text-gray-700'>{product.order_count.toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  )
}

export default EcomerceProductReport
