'use client';

import { api } from '@/lib/api';
import { useAuth } from '@/lib/auth';
import { DashboardResponse, DashboardStats } from '@/types/common';
import {
    Chart as ChartJS,
    ArcElement,
    Tooltip,
    Legend,
    CategoryScale,
    LinearScale,
    BarElement,
} from 'chart.js';
import { Cylinder, Warehouse, Truck, Plus, ArrowRight, BarChart3, Clock } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { Doughnut, Bar } from 'react-chartjs-2';
import ProtectedRoute from '@/lib/ProtectedRoute';

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

const ManufacturerDashboardPage = () => {
    const [stats, setStats] = useState<DashboardStats | null>(null);
    const [loading, setLoading] = useState(true);
    const [selectedCylinderIds, setSelectedCylinderIds] = useState<string[]>([]);
    const { user } = useAuth();
    const router = useRouter();

    const [currentTime, setCurrentTime] = useState(new Date());

    useEffect(() => {
        const timer = setInterval(() => setCurrentTime(new Date()), 1000);
        return () => clearInterval(timer);
    }, []);

    useEffect(() => {
        if (user && user.role !== 'MANUFACTURER') {
            router.push('/dashboard');
            return;
        }

        const fetchStats = async () => {
            try {
                const response = await api.get<DashboardResponse>('/dashboard');
                setStats(response.data);
            } catch (error) {
                console.error('Failed to fetch dashboard stats', error);
            } finally {
                setLoading(false);
            }
        };

        fetchStats();
    }, [user, router]);

    const doughnutData = {
        labels: ['Claimed', 'Left'],
        datasets: [
            {
                data: [stats?.claimedCylinders || 0, stats?.leftCylinders || 0],
                backgroundColor: ['#10B981', '#F43F5E'],
                hoverBackgroundColor: ['#059669', '#E11D48'],
                borderColor: ['#ffffff', '#ffffff'],
                borderWidth: 2,
            },
        ],
    };

    const barData = {
        labels: ['Total', 'Claimed', 'Left'],
        datasets: [
            {
                label: 'Cylinders',
                data: [
                    stats?.totalCylinders || 0,
                    stats?.claimedCylinders || 0,
                    stats?.leftCylinders || 0,
                ],
                backgroundColor: 'rgba(59, 130, 246, 0.6)',
                borderColor: 'rgb(59, 130, 246)',
                borderWidth: 1,
                borderRadius: 8,
            },
        ],
    };

    if (loading) {
        return (
            <div className="flex justify-center items-center min-h-screen bg-gray-50">
                <div className="flex flex-col items-center space-y-4">
                    <div className="w-12 h-12 border-4 border-[#dd3a3f] border-t-transparent rounded-full animate-spin"></div>
                    <p className="text-gray-600 font-medium">Preparing your dashboard...</p>
                </div>
            </div>
        );
    }

    return (
        <ProtectedRoute>
            <div className="min-h-screen bg-gray-50 p-4 sm:p-6 lg:p-8 space-y-8">

                {/* Stat Cards */}
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                    <SummaryCard
                        icon={Cylinder}
                        title="Total Cylinder"
                        value={stats?.totalCylinders || 0}
                        color="bg-blue-600"
                    />
                    <SummaryCard
                        icon={Warehouse}
                        title="Claimed by Plants"
                        value={stats?.claimedCylinders || 0}
                        color="bg-emerald-600"
                    />
                    <SummaryCard
                        icon={Truck}
                        title="Cylinder Left"
                        value={stats?.leftCylinders || 0}
                        color="bg-rose-600"
                    />
                </div>

                {/* Main Content Grid */}
                <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
                    {/* Charts Panel */}
                    <div className="lg:col-span-8 grid grid-cols-1 md:grid-cols-2 gap-6">
                        <ChartCard title="Cylinder Distribution">
                            <div className="h-64 flex items-center justify-center">
                                <Doughnut data={doughnutData} options={{
                                    maintainAspectRatio: false,
                                    plugins: { legend: { position: 'bottom' } }
                                }} />
                            </div>
                        </ChartCard>
                        <ChartCard title="Cylinder Overview">
                            <div className="h-64 flex items-center justify-center">
                                <Bar data={barData} options={{
                                    maintainAspectRatio: false,
                                    plugins: { legend: { display: false } },
                                    scales: { y: { beginAtZero: true } }
                                }} />
                            </div>
                        </ChartCard>
                    </div>

                    {/* Quick Navigation Panel */}
                    <div className="lg:col-span-4 flex flex-col gap-6">
                        <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 flex-1">
                            <h2 className="text-lg font-bold text-gray-900 mb-6 flex items-center gap-2">
                                <BarChart3 className="w-5 h-5 text-[#dd3a3f]" />
                                Quick Actions
                            </h2>
                            <div className="space-y-3">
                                <QuickActionButton
                                    href="/cylinder"
                                    icon={Cylinder}
                                    label="Manage Cylinders"
                                    description="View and update your stock"
                                />

                                <QuickActionButton
                                    href="/profile"
                                    icon={Warehouse}
                                    label="My Profile"
                                    description="Update your account details"
                                />
                            </div>
                        </div>
                    </div>
                </div>


            </div>
        </ProtectedRoute>
    );
};

const SummaryCard = ({ icon: Icon, title, value, color, trend }: { icon: any, title: string, value: number, color: string, trend?: string }) => (

    <div className="bg-white p-6 rounded-xl shadow-lg flex items-center space-x-4">
        <div className={`p-3 rounded-full text-white ${color}`}>
            <Icon className="w-6 h-6" />
        </div>
        <div>
            <p className="text-sm text-gray-500 font-medium">{title}</p>
            <p className="text-3xl font-bold text-gray-800">{value}</p>
        </div>
    </div>

);

const ChartCard = ({ title, children }: { title: string, children: React.ReactNode }) => (
    <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
        <h3 className="text-lg font-bold text-gray-900 mb-6">{title}</h3>
        {children}
    </div>
);

const QuickActionButton = ({ href, icon: Icon, label, description }: { href: string, icon: any, label: string, description: string }) => (
    <Link href={href} className="flex items-center gap-4 p-4 rounded-xl border border-gray-50 hover:border-[#dd3a3f] hover:bg-red-50/30 transition-all group">
        <div className="p-2.5 rounded-lg bg-gray-50 group-hover:bg-[#dd3a3f] transition-all">
            <Icon className="w-5 h-5 text-gray-500 group-hover:text-white" />
        </div>
        <div className="flex-1">
            <p className="text-sm font-bold text-gray-900 group-hover:text-[#dd3a3f] transition-all">{label}</p>
            <p className="text-xs text-gray-500">{description}</p>
        </div>
        <ArrowRight className="w-4 h-4 text-gray-300 group-hover:text-[#dd3a3f] translate-x-0 group-hover:translate-x-1 transition-all" />
    </Link>
);

export default ManufacturerDashboardPage;
