import { useState } from 'react';
import { useEquipmentStore } from '@/stores/equipmentStore';
import { SectionTitle, StatsCard } from '@/components/common';
import { formatCurrency } from '@/lib/formatters';
import { Bar, Doughnut, Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, LineElement, PointElement, ArcElement, Tooltip, Legend } from 'chart.js';
import { defaultChartOptions, doughnutOptions, barChartOptions } from '@/lib/chartConfig';
import { TrendingUp, TrendingDown, IndianRupee, ShoppingCart, Package } from 'lucide-react';

ChartJS.register(CategoryScale, LinearScale, BarElement, LineElement, PointElement, ArcElement, Tooltip, Legend);

export default function SalesDashboardScreen() {
  const { salesSummary, transactions, items } = useEquipmentStore();
  const [period, setPeriod] = useState<'month' | 'quarter' | 'year'>('month');

  const revenueVsCostData = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    datasets: [
      { label: 'Revenue', data: [8000, 12000, 15000, 10000, 18000, 51200], backgroundColor: '#F26522', borderRadius: 6, barThickness: 16 },
      { label: 'Cost', data: [5000, 8000, 10000, 7000, 12000, 33500], backgroundColor: '#E5E7EB', borderRadius: 6, barThickness: 16 },
    ],
  };

  const profitTrendData = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    datasets: [{
      label: 'Profit',
      data: [3000, 4000, 5000, 3000, 6000, 17700],
      borderColor: '#10B981',
      backgroundColor: 'rgba(16,185,129,0.1)',
      fill: true,
      tension: 0.4,
      pointRadius: 4,
      pointBackgroundColor: '#10B981',
    }],
  };

  const categoryData = {
    labels: ['Skates', 'Helmets', 'Pads', 'Guards', 'Wheels'],
    datasets: [{
      data: [5600, 4800, 1800, 2500, 3000],
      backgroundColor: ['#F26522', '#D2232A', '#FFC72C', '#10B981', '#6366F1'],
      borderWidth: 0,
    }],
  };

  const sellTrans = transactions.filter(t => t.type === 'sell');
  const inventoryValue = items.reduce((s, i) => s + i.currentStock * i.unitCost, 0);

  return (
    <div className="px-4 pt-4 pb-4 space-y-5">
      {/* Profit Summary */}
      <div className="bg-white rounded-2xl p-5 card-shadow">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-base font-bold text-gray-900">Overall Profit/Loss</h3>
          <div className="flex bg-gray-100 rounded-full p-0.5">
            {(['month', 'quarter', 'year'] as const).map(p => (
              <button key={p} onClick={() => setPeriod(p)} className={`px-3 py-1 rounded-full text-[10px] font-medium transition-all ${period === p ? 'brand-gradient text-white' : 'text-gray-500'}`}>
                {p === 'month' ? 'Month' : p === 'quarter' ? 'Quarter' : 'Year'}
              </button>
            ))}
          </div>
        </div>
        <div className="text-center">
          <p className={`text-4xl font-extrabold ${salesSummary.profit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>
            {formatCurrency(salesSummary.profit)}
          </p>
          <div className="flex items-center justify-center gap-1 mt-1">
            {salesSummary.profit >= 0 ? <TrendingUp className="w-4 h-4 text-emerald-500" /> : <TrendingDown className="w-4 h-4 text-red-500" />}
            <span className={`text-sm font-medium ${salesSummary.profit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>{salesSummary.profitMargin}% margin</span>
          </div>
        </div>
        <div className="grid grid-cols-3 gap-3 mt-4 pt-4 border-t border-gray-100">
          <div className="text-center">
            <p className="text-lg font-bold text-gray-900">{formatCurrency(salesSummary.revenue).replace('\u20b9', '')}</p>
            <p className="text-[10px] text-gray-400">Revenue</p>
          </div>
          <div className="text-center">
            <p className="text-lg font-bold text-gray-900">{formatCurrency(salesSummary.cost).replace('\u20b9', '')}</p>
            <p className="text-[10px] text-gray-400">Cost</p>
          </div>
          <div className="text-center">
            <p className="text-lg font-bold text-emerald-600">{formatCurrency(salesSummary.profit).replace('\u20b9', '')}</p>
            <p className="text-[10px] text-gray-400">Profit</p>
          </div>
        </div>
      </div>

      {/* Revenue vs Cost Chart */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Revenue vs Cost" />
        <div className="h-52">
          <Bar data={revenueVsCostData} options={barChartOptions} />
        </div>
      </div>

      {/* Profit Trend */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Profit Trend" />
        <div className="h-44">
          <Line data={profitTrendData} options={defaultChartOptions} />
        </div>
      </div>

      {/* Profit by Category */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Profit by Category" />
        <div className="h-52 flex items-center justify-center">
          <div className="w-40 h-40">
            <Doughnut data={categoryData} options={doughnutOptions} />
          </div>
        </div>
      </div>

      {/* Inventory Value */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Inventory Value" />
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 bg-orange-50 rounded-xl flex items-center justify-center">
            <Package className="w-7 h-7 text-orange-500" />
          </div>
          <div>
            <p className="text-2xl font-bold text-gray-900">{formatCurrency(inventoryValue)}</p>
            <p className="text-xs text-gray-400">{items.length} items &bull; {items.reduce((s, i) => s + i.currentStock, 0)} total units</p>
          </div>
        </div>
      </div>

      {/* Recent Transactions */}
      <div>
        <SectionTitle title="Recent Transactions" />
        <div className="space-y-2">
          {transactions.slice(0, 6).map(t => (
            <div key={t.id} className="bg-white rounded-xl p-3 card-shadow flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className={`w-9 h-9 rounded-lg flex items-center justify-center ${t.type === 'buy' ? 'bg-blue-50' : 'bg-emerald-50'}`}>
                  {t.type === 'buy' ? <ShoppingCart className="w-4 h-4 text-blue-500" /> : <IndianRupee className="w-4 h-4 text-emerald-500" />}
                </div>
                <div>
                  <p className="text-sm font-medium text-gray-900">{t.equipmentName}</p>
                  <p className="text-[10px] text-gray-400">{t.transactionDate} &bull; {t.buyerSeller}</p>
                </div>
              </div>
              <div className="text-right">
                <p className="text-sm font-bold text-gray-900">{formatCurrency(t.totalAmount)}</p>
                {t.profit !== undefined && (
                  <p className={`text-[10px] font-medium ${t.profit >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>
                    {t.profit >= 0 ? '+' : ''}{formatCurrency(t.profit)}
                  </p>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
