'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Header from '@/components/Header';
import { useLocale } from '@/lib/i18n/LocaleContext';
import { useUser } from '@/lib/auth/UserContext';
import styles from './page.module.css';
import { TrendsChart, HotelComparisonChart } from './ChartComponents';

interface Metrics {
  totalCommissionsPaid: number;
  avgAchievement: number;
  budgetCap: number;
  activeBudgetUtilization: number;
  clawbacks: number;
}

interface TrendData {
  period: string;
  paid: number;
  cap: number;
}

interface HotelData {
  hotel: string;
  sales: number;
  commissions: number;
}

export default function DashboardPage() {
  const router = useRouter();
  const { t, locale } = useLocale();
  const { role, isLoading: authLoading } = useUser();

  const [metrics, setMetrics] = useState<Metrics | null>(null);
  const [trends, setTrends] = useState<TrendData[]>([]);
  const [hotelData, setHotelData] = useState<HotelData[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const isRoleAuthorized = role === 'admin' || role === 'director' || role === 'analyst';

  const fetchDashboardData = async () => {
    setIsLoading(true);
    try {
      const res = await fetch('/api/analytics/dashboard');
      if (res.ok) {
        const data = await res.json();
        setMetrics(data.metrics);
        setTrends(data.trends || []);
        setHotelData(data.hotelPerformance || []);
      }
    } catch (err) {
      console.error('Failed to fetch dashboard analytics data', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (!authLoading && !isRoleAuthorized) {
      router.push('/unauthorized');
    }
  }, [role, authLoading, router, isRoleAuthorized]);

  useEffect(() => {
    if (isRoleAuthorized) {
      fetchDashboardData();
    }
  }, [role, isRoleAuthorized]);

  const formatCurrency = (val: number) => {
    return new Intl.NumberFormat(locale === 'es' ? 'es-CO' : 'en-US', {
      style: 'currency',
      currency: 'USD',
      maximumFractionDigits: 0
    }).format(val);
  };

  const formatPercent = (val: number) => {
    return `${(val * 100).toFixed(1)}%`;
  };

  if (authLoading || (!isRoleAuthorized && role !== null)) {
    return <div className={styles.loading}>Verificando credenciales...</div>;
  }

  if (!isRoleAuthorized) {
    return null; // Redirecting...
  }

  // Circular progress math
  const radius = 24;
  const circumference = 2 * Math.PI * radius;
  const achievementRate = metrics?.avgAchievement || 0;
  const strokeDashoffset = circumference - (Math.min(achievementRate, 1) * circumference);

  return (
    <div className={styles.container}>
      <Header activeTab="dashboard" />
      <main className={styles.main} id="dashboard-main-view">
        <div className={styles.titleSection}>
          <h1 className={styles.title}>{t('dashboard.title')}</h1>
        </div>

        {isLoading ? (
          <div className={styles.loading}>Cargando panel de control...</div>
        ) : (
          <>
            {/* KPI Cards Grid */}
            <div className={styles.metricsGrid}>
              {/* Card 1: Total Commissions */}
              <div className={styles.metricCard}>
                <div className={styles.metricInfo}>
                  <span className={styles.metricLabel}>{t('dashboard.total_paid')}</span>
                  <span className={styles.metricValue}>
                    {metrics ? formatCurrency(metrics.totalCommissionsPaid) : '$0'}
                  </span>
                </div>
                <div style={{ color: 'var(--primary)', fontSize: '1.5rem' }}>💰</div>
              </div>

              {/* Card 2: Avg Achievement Rate */}
              <div className={styles.metricCard}>
                <div className={styles.metricInfo}>
                  <span className={styles.metricLabel}>{t('dashboard.avg_achievement')}</span>
                  <span className={styles.metricValue}>
                    {metrics ? formatPercent(metrics.avgAchievement) : '0%'}
                  </span>
                </div>
                <div className={styles.progressCircleWrapper}>
                  <svg className={styles.progressSvg}>
                    <circle
                      className={styles.circleBackground}
                      cx="30"
                      cy="30"
                      r={radius}
                    />
                    <circle
                      className={styles.circleFill}
                      cx="30"
                      cy="30"
                      r={radius}
                      strokeDasharray={circumference}
                      strokeDashoffset={strokeDashoffset}
                    />
                  </svg>
                  <span className={styles.progressText}>
                    {metrics ? `${Math.round(metrics.avgAchievement * 100)}` : '0'}%
                  </span>
                </div>
              </div>

              {/* Card 3: Budget Utilization */}
              <div className={styles.metricCard}>
                <div className={styles.metricInfo}>
                  <span className={styles.metricLabel}>{t('dashboard.budget_cap')}</span>
                  <span className={styles.metricValue}>
                    {metrics ? formatCurrency(metrics.budgetCap) : '$0'}
                  </span>
                  <span style={{ fontSize: '0.75rem', opacity: 0.6 }}>
                    Uso: {metrics ? formatPercent(metrics.activeBudgetUtilization) : '0%'}
                  </span>
                </div>
                <div style={{ color: 'var(--secondary)', fontSize: '1.5rem' }}>📊</div>
              </div>

              {/* Card 4: Clawbacks */}
              <div className={styles.metricCard}>
                <div className={styles.metricInfo}>
                  <span className={styles.metricLabel}>{t('history.adjustment')}</span>
                  <span className={styles.metricValue}>
                    {metrics ? formatCurrency(metrics.clawbacks) : '$0'}
                  </span>
                </div>
                <div style={{ color: 'hsl(0, 75%, 45%)', fontSize: '1.5rem' }}>🔄</div>
              </div>
            </div>

            {/* Charts Section */}
            <div className={styles.chartsGrid}>
              <div className={styles.chartCard}>
                <h3 className={styles.chartTitle}>{t('dashboard.trends')}</h3>
                <span className={styles.chartDesc}>{t('dashboard.trends_desc')}</span>
                <TrendsChart trendData={trends} locale={locale} />
              </div>

              <div className={styles.chartCard}>
                <h3 className={styles.chartTitle}>{t('dashboard.hotels_comparison')}</h3>
                <span className={styles.chartDesc}>{t('dashboard.hotels_desc')}</span>
                <HotelComparisonChart hotelData={hotelData} locale={locale} />
              </div>
            </div>
          </>
        )}
      </main>
    </div>
  );
}
