// /media/hf/data/projects/Dawinder/transport/app/(dashboard)/reports/page.tsx
"use client";

import React, { useEffect } from 'react';
import { useAuth } from '@/context/AuthContext';
import { useRouter } from 'next/navigation';
import MetricCard from '@/components/ui/MetricCard';
import { mockTrips, mockExpenses } from '@/lib/mockData';
import { formatCurrency } from '@/lib/utils';
import { TrendingUp, TrendingDown, PieChart, IndianRupee } from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer, Cell } from 'recharts';

export default function ReportsPage() {
  const { role } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (role !== 'transport_admin') {
      router.push('/dashboard');
    }
  }, [role, router]);

  if (role !== 'transport_admin') return null;

  const totalRevenue = mockTrips.filter(t => t.status === 'completed').reduce((sum, t) => sum + t.freightAmount, 0);
  const totalExpenses = mockExpenses.filter(e => e.status === 'approved').reduce((sum, e) => sum + e.amount, 0);
  const netProfit = totalRevenue - totalExpenses;
  const margin = totalRevenue > 0 ? ((netProfit / totalRevenue) * 100).toFixed(1) : '0.0';

  // Mock monthly data for chart
  const monthlyData = [
    { name: 'Jan', revenue: 150000, profit: 45000 },
    { name: 'Feb', revenue: 180000, profit: 55000 },
    { name: 'Mar', revenue: 210000, profit: 70000 },
    { name: 'Apr', revenue: 190000, profit: 60000 },
    { name: 'May', revenue: totalRevenue, profit: netProfit },
  ];

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-text-primary">Profitability Reports</h1>
          <p className="text-text-muted text-sm mt-1">Financial overview and analytics</p>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <MetricCard label="Total Revenue" value={formatCurrency(totalRevenue)} color="green" icon={<TrendingUp size={20} />} />
        <MetricCard label="Total Expenses" value={formatCurrency(totalExpenses)} color="red" icon={<IndianRupee size={20} />} />
        <MetricCard label="Net Profit" value={formatCurrency(netProfit)} color="amber" icon={<PieChart size={20} />} />
        <MetricCard label="Profit Margin" value={`${margin}%`} color="blue" icon={<TrendingUp size={20} />} />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-surface border border-border rounded-xl p-6">
          <h3 className="text-lg font-semibold text-text-primary mb-6">Monthly Revenue & Profit</h3>
          <div className="h-80 w-full">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={monthlyData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#21262d" vertical={false} />
                <XAxis dataKey="name" stroke="#8b949e" tickLine={false} axisLine={false} />
                <YAxis stroke="#8b949e" tickLine={false} axisLine={false} tickFormatter={(value) => `₹${value / 1000}k`} />
                <RechartsTooltip 
                  cursor={{ fill: 'transparent' }}
                  contentStyle={{ backgroundColor: '#161b22', borderColor: '#21262d', borderRadius: '0.5rem', color: '#e6edf3' }}
                  formatter={(value: number) => [formatCurrency(value), '']}
                />
                <Bar dataKey="revenue" name="Revenue" fill="#F59E0B" radius={[4, 4, 0, 0]} />
                <Bar dataKey="profit" name="Profit" fill="#34d399" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        <div className="bg-surface border border-border rounded-xl p-6">
          <h3 className="text-lg font-semibold text-text-primary mb-6">Vehicle-wise Profitability</h3>
          <div className="space-y-4">
            {[
              { id: 'MH-12 AB 4532', profit: 45000, margin: 32 },
              { id: 'DL-01 GH 9021', profit: 38000, margin: 28 },
              { id: 'KA-05 MM 3310', profit: 32000, margin: 25 },
              { id: 'UP-32 XY 8899', profit: 28000, margin: 22 },
              { id: 'GJ-01 KL 4455', profit: 25000, margin: 20 },
            ].map((v, i) => (
              <div key={v.id} className="flex flex-col">
                <div className="flex justify-between items-center mb-1">
                  <span className="text-sm font-medium text-text-primary">{v.id}</span>
                  <span className="text-sm font-bold text-status-green">{formatCurrency(v.profit)}</span>
                </div>
                <div className="flex items-center space-x-2">
                  <div className="flex-1 bg-background rounded-full h-2">
                    <div 
                      className="bg-primary h-2 rounded-full" 
                      style={{ width: `${v.margin}%` }}
                    ></div>
                  </div>
                  <span className="text-xs text-text-muted w-8 text-right">{v.margin}%</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
