'use client'

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

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

const DashboardCRM = () => {
  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 { data: analytics, isLoading } = useSalesAnalytics({
    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)
  }

  // Format date
  const formatDate = (dateString: any) => {
    return new Date(dateString).toLocaleDateString('id-ID', {
      month: 'short',
      day: 'numeric'
    })
  }

  // Format long date
  const formatLongDate = (dateString: any) => {
    return new Date(dateString).toLocaleDateString('id-ID', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  }

  // Prepare chart data
  const chartData = analytics?.data.map((item: any) => ({
    date: formatDate(item.date),
    sales: item.sales,
    orders: item.orders,
    items: item.items,
    averageOrderValue: item.orders > 0 ? Math.round(item.sales / item.orders) : 0
  }))

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

  // Metric cards data
  const metrics = [
    {
      title: 'Total Sales',
      value: formatCurrency(analytics?.summary.total_sales),
      icon: 'currency-dollar',
      color: 'text-green-600',
      bgColor: 'bg-green-50',
      change: '+12.5%',
      changeColor: 'text-green-600'
    },
    {
      title: 'Total Orders',
      value: analytics?.summary.total_orders.toLocaleString(),
      icon: 'shopping-cart',
      color: 'text-blue-600',
      bgColor: 'bg-blue-50',
      change: '+8.2%',
      changeColor: 'text-blue-600'
    },
    {
      title: 'Total Items',
      value: analytics?.summary.total_items.toLocaleString(),
      icon: 'package',
      color: 'text-purple-600',
      bgColor: 'bg-purple-50',
      change: '+15.1%',
      changeColor: 'text-purple-600'
    },
    {
      title: 'Average Order Value',
      value: formatCurrency(analytics?.summary.average_order_value),
      icon: 'trending-up',
      color: 'text-orange-600',
      bgColor: 'bg-orange-50',
      change: '+4.3%',
      changeColor: 'text-orange-600'
    }
  ]

  // Performance data for pie chart
  const performanceData = analytics?.data.map((item: any, index: any) => ({
    name: formatDate(item.date),
    value: item.sales,
    color: colors[index % colors.length]
  }))

  if (isLoading) return <Loading />

  return (
    <div className='mx-auto space-y-6'>
      {/* Header */}
      <div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-8'>
        <div>
          <h1 className='text-4xl font-bold text-gray-800 mb-2'>Sales Analytics Dashboard</h1>
          <PickerBasic dateFrom={dateFrom} dateTo={dateTo} onChangeDateFrom={setDateFrom} onChangeDateTo={setDateTo} />
        </div>
        <div className='flex gap-3'>
          <div className='flex items-center gap-2 bg-blue-50 px-4 py-2 rounded-full'>
            <TablerIcon name='calendar' className='text-blue-600 text-sm' />
            <span className='text-blue-700 font-medium'>Grouped by {analytics?.group_by}</span>
          </div>
          <div className='flex items-center gap-2 bg-purple-50 px-4 py-2 rounded-full'>
            <TablerIcon name='chart-line' className='text-purple-600 text-sm' />
            <span className='text-purple-700 font-medium'>{analytics?.data.length} data points</span>
          </div>
        </div>
      </div>

      {/* Metrics 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-3'>{metric.value}</h3>
                  <div className='flex items-center gap-1'>
                    <TablerIcon name='trending-up' className={`text-xs ${metric.changeColor}`} />
                    <span className={`text-sm font-medium ${metric.changeColor}`}>{metric.change}</span>
                  </div>
                </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 lg:grid-cols-3 gap-6'>
        {/* Sales Trend Chart */}
        <div className='lg: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-line' className='text-blue-600 text-2xl' />
              <h2 className='text-xl font-semibold text-gray-800'>Sales Trend</h2>
            </div>
            <div className='h-80'>
              <ResponsiveContainer width='100%' height='100%'>
                <LineChart data={chartData}>
                  <CartesianGrid strokeDasharray='3 3' stroke='#f0f0f0' />
                  <XAxis dataKey='date' stroke='#6b7280' />
                  <YAxis tickFormatter={value => `${(value / 1000).toFixed(0)}K`} stroke='#6b7280' />
                  <Tooltip
                    formatter={(value, name) => [
                      name === 'sales' ? formatCurrency(value) : value.toLocaleString(),
                      name === 'sales' ? 'Sales' : name === 'orders' ? 'Orders' : 'Items'
                    ]}
                    contentStyle={{
                      backgroundColor: '#fff',
                      border: '1px solid #e5e7eb',
                      borderRadius: '8px',
                      boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)'
                    }}
                  />
                  <Line
                    type='monotone'
                    dataKey='sales'
                    stroke='#3B82F6'
                    strokeWidth={3}
                    dot={{ fill: '#3B82F6', strokeWidth: 2, r: 5 }}
                    activeDot={{ r: 7, stroke: '#3B82F6', strokeWidth: 2 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>

        {/* Sales 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'>Sales Distribution</h2>
            </div>
            <div className='h-80'>
              <ResponsiveContainer width='100%' height='100%'>
                <PieChart>
                  <Pie
                    data={performanceData}
                    cx='50%'
                    cy='50%'
                    outerRadius={90}
                    dataKey='value'
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  >
                    {performanceData?.map((entry: any, index: any) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={value => [formatCurrency(value), 'Sales']}
                    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>

      {/* Orders & Items 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-bar' className='text-green-600 text-2xl' />
            <h2 className='text-xl font-semibold text-gray-800'>Orders & Items Analysis</h2>
          </div>
          <div className='h-80'>
            <ResponsiveContainer width='100%' height='100%'>
              <BarChart data={chartData}>
                <CartesianGrid strokeDasharray='3 3' stroke='#f0f0f0' />
                <XAxis dataKey='date' stroke='#6b7280' />
                <YAxis stroke='#6b7280' />
                <Tooltip
                  contentStyle={{
                    backgroundColor: '#fff',
                    border: '1px solid #e5e7eb',
                    borderRadius: '8px',
                    boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)'
                  }}
                />
                <Bar dataKey='orders' fill='#10B981' name='Orders' radius={[4, 4, 0, 0]} />
                <Bar dataKey='items' fill='#3B82F6' name='Items' radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>

      {/* Detailed Data Table */}
      <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='table' className='text-indigo-600 text-2xl' />
            <h2 className='text-xl font-semibold text-gray-800'>Daily Performance Details</h2>
          </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'>Date</th>
                  <th className='text-right py-4 px-6 font-semibold text-gray-700'>Sales</th>
                  <th className='text-right py-4 px-6 font-semibold text-gray-700'>Orders</th>
                  <th className='text-right py-4 px-6 font-semibold text-gray-700'>Items</th>
                  <th className='text-right py-4 px-6 font-semibold text-gray-700'>Avg Order Value</th>
                  <th className='text-right py-4 px-6 font-semibold text-gray-700'>Net Sales</th>
                </tr>
              </thead>
              <tbody>
                {analytics?.data.map((row: any, index: any) => (
                  <tr key={index} className='border-b border-gray-100 hover:bg-gray-50 transition-colors'>
                    <td className='py-4 px-6 font-medium text-gray-800'>{formatLongDate(row.date)}</td>
                    <td className='py-4 px-6 text-right font-semibold text-green-600'>{formatCurrency(row.sales)}</td>
                    <td className='py-4 px-6 text-right text-gray-700'>{row.orders.toLocaleString()}</td>
                    <td className='py-4 px-6 text-right text-gray-700'>{row.items.toLocaleString()}</td>
                    <td className='py-4 px-6 text-right font-medium text-gray-800'>
                      {formatCurrency(row.orders > 0 ? Math.round(row.sales / row.orders) : 0)}
                    </td>
                    <td className='py-4 px-6 text-right font-semibold text-gray-800'>
                      {formatCurrency(row.net_sales)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Summary Footer */}
      <div className='bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl border border-blue-100'>
        <div className='p-6'>
          <div className='grid grid-cols-2 md:grid-cols-4 gap-6'>
            <div className='text-center'>
              <h3 className='text-2xl font-bold text-gray-800 mb-1'>{formatCurrency(analytics?.summary.net_sales)}</h3>
              <p className='text-gray-600 font-medium'>Net Sales</p>
            </div>
            <div className='text-center'>
              <h3 className='text-2xl font-bold text-gray-800 mb-1'>{analytics?.summary.total_orders}</h3>
              <p className='text-gray-600 font-medium'>Total Orders</p>
            </div>
            <div className='text-center'>
              <h3 className='text-2xl font-bold text-gray-800 mb-1'>{formatCurrency(analytics?.summary.total_tax)}</h3>
              <p className='text-gray-600 font-medium'>Total Tax</p>
            </div>
            <div className='text-center'>
              <h3 className='text-2xl font-bold text-gray-800 mb-1'>
                {formatCurrency(analytics?.summary.total_discount)}
              </h3>
              <p className='text-gray-600 font-medium'>Total Discount</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default DashboardCRM
