'use strict';
'use client';

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

interface SimulatedItem {
  main: {
    period: string;
    planId: number;
    userId: number;
    salesAmount: number;
    goalAmount: number;
    achievementPercentage: number;
    calculatedCommission: number;
    calculatedBonus: number;
    adjustmentAmount: number;
    totalPayout: number;
    status: string;
    adjustmentNotes: string | null;
  };
  adjustments: Array<{
    period: string;
    adjustmentAmount: number;
    adjustmentNotes: string;
  }>;
  aiAudited?: boolean;
  aiAuditNotes?: {
    en: string | null;
    es: string | null;
  } | null;
}

interface User {
  id: number;
  username: string;
  role: string;
}

export default function SimulationPage() {
  const router = useRouter();
  const { locale, t } = useLocale();
  const { role, user: currentUser, isLoading: contextLoading } = useUser();

  // Form State
  const [period, setPeriod] = useState('2026-06');
  const [simulateOnly, setSimulateOnly] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);

  // Results State
  const [results, setResults] = useState<SimulatedItem[]>([]);
  const [summary, setSummary] = useState({
    count: 0,
    totalCommission: 0,
    totalAdjustment: 0
  });

  // User Map to map userId to User Details
  const [usersMap, setUsersMap] = useState<Record<number, any>>({});
  const [plansMap, setPlansMap] = useState<Record<number, any>>({});

  useEffect(() => {
    if (!contextLoading) {
      if (!currentUser) {
        router.push('/login');
        return;
      }
      if (role !== 'admin' && role !== 'analyst') {
        router.push('/unauthorized');
        return;
      }
    }
  }, [contextLoading, currentUser, role, router]);

  useEffect(() => {
    if (contextLoading || !currentUser || (role !== 'admin' && role !== 'analyst')) {
      return;
    }

    // Load users list for username mapping
    fetch('/api/users')
      .then((res) => (res.ok ? res.json() : { users: [] }))
      .then((data) => {
        const mapping: Record<number, any> = {};
        data.users.forEach((u: any) => {
          mapping[u.id] = u;
        });
        setUsersMap(mapping);
      })
      .catch((err) => console.error('Failed to fetch users mapping:', err));

    // Load plans list for plan version mapping
    fetch('/api/plans')
      .then((res) => (res.ok ? res.json() : { plans: [] }))
      .then((data) => {
        const mapping: Record<number, any> = {};
        data.plans.forEach((p: any) => {
          mapping[p.id] = p;
        });
        setPlansMap(mapping);
      })
      .catch((err) => console.error('Failed to fetch plans mapping:', err));
  }, []);

  const handleCalculate = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSuccess(null);
    setResults([]);
    setSummary({ count: 0, totalCommission: 0, totalAdjustment: 0 });

    if (!period || !/^\d{4}-\d{2}$/.test(period)) {
      setError('El período debe tener el formato YYYY-MM.');
      return;
    }

    setIsProcessing(true);
    try {
      const res = await fetch('/api/settlements/calculate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ period, simulateOnly })
      });

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Error al procesar el cálculo.');
        return;
      }

      setResults(data.simulated || []);
      setSummary({
        count: data.metadata.count,
        totalCommission: data.metadata.totalCommission,
        totalAdjustment: data.metadata.totalAdjustment
      });

      if (simulateOnly) {
        setSuccess('Simulación completada con éxito. Los resultados no se han guardado.');
      } else {
        setSuccess('Liquidaciones calculadas y guardadas correctamente.');
      }
    } catch (err: any) {
      console.error('Calculation fetch error:', err);
      setError('Error al comunicarse con el servidor.');
    } finally {
      setIsProcessing(false);
    }
  };

  if (contextLoading) {
    return (
      <div className={styles.container}>
        <Header activeTab="simulation" />
        <div className={styles.mainContent}>
          <p>Cargando panel de simulación...</p>
        </div>
      </div>
    );
  }

  // Segmented block if unauthorized
  if (role !== 'admin' && role !== 'analyst') {
    return (
      <div className={styles.container}>
        <Header activeTab="simulation" />
        <div className={styles.mainContent}>
          <div className={styles.card}>
            <h1 className={styles.title} style={{ color: '#f87171' }}>Acceso Restringido</h1>
            <p className={styles.description}>
              Lo sentimos, esta sección es exclusiva para el Administrador y el Analista de Compensaciones.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <Header activeTab="simulation" />
      <main className={styles.mainContent}>
        <div className={styles.titleSection}>
          <h1 className={styles.title}>{t('simulation.title')}</h1>
          <p className={styles.description}>{t('simulation.description')}</p>
        </div>

        <div className={styles.card}>
          <form onSubmit={handleCalculate} className={styles.formGrid}>
            <div className={styles.formGroup}>
              <label htmlFor="sim-period" className={styles.label}>
                {t('simulation.periodLabel')}
              </label>
              <input
                type="text"
                id="sim-period"
                className={styles.input}
                value={period}
                onChange={(e) => setPeriod(e.target.value)}
                placeholder="2026-06"
                required
              />
            </div>

            <div className={styles.formGroup}>
              <div className={styles.toggleContainer}>
                <input
                  type="checkbox"
                  id="sim-dry-run"
                  className={styles.checkbox}
                  checked={simulateOnly}
                  onChange={(e) => setSimulateOnly(e.target.checked)}
                />
                <label htmlFor="sim-dry-run" className={styles.checkboxLabel}>
                  {t('simulation.dryRunLabel')}
                </label>
              </div>
            </div>

            <button
              type="submit"
              id="btn-run-simulation"
              className={styles.btn}
              disabled={isProcessing}
            >
              {isProcessing ? t('simulation.calculatingBtn') : t('simulation.calculateBtn')}
            </button>
          </form>
        </div>

        {error && <div className={styles.errorMsg} id="simulation-error-msg">{error}</div>}
        {success && <div className={styles.successMsg} id="simulation-success-msg">{success}</div>}

        {results.length > 0 && (
          <div className={styles.card}>
            <div className={styles.resultsHeader}>
              <h2 className={styles.resultsTitle}>{t('simulation.resultsHeader')}</h2>
            </div>

            <div className={styles.summaryCards}>
              <div className={styles.summaryCard}>
                <div className={styles.summaryLabel}>{t('simulation.summaryCollaborators')}</div>
                <div className={styles.summaryVal}>{summary.count}</div>
              </div>
              <div className={styles.summaryCard}>
                <div className={styles.summaryLabel}>{t('simulation.summaryCommission')}</div>
                <div className={styles.summaryVal}>
                  ${summary.totalCommission.toLocaleString('es-CO', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </div>
              </div>
              <div className={styles.summaryCard}>
                <div className={styles.summaryLabel}>{t('simulation.summaryAdjustment')}</div>
                <div className={`${styles.summaryVal} ${summary.totalAdjustment < 0 ? styles.negative : styles.positive}`}>
                  ${summary.totalAdjustment.toLocaleString('es-CO', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </div>
              </div>
              <div className={styles.summaryCard}>
                <div className={styles.summaryLabel}>{t('simulation.summaryPayout')}</div>
                <div className={styles.summaryVal}>
                  ${(summary.totalCommission + summary.totalAdjustment).toLocaleString('es-CO', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </div>
              </div>
            </div>

            <div className={styles.tableWrapper}>
              <table className={styles.table} id="simulation-table">
                <thead>
                  <tr>
                    <th className={styles.th}>{t('simulation.thCollaborator')}</th>
                    <th className={styles.th}>{t('simulation.thPlan')}</th>
                    <th className={styles.th}>{t('simulation.thGoal')}</th>
                    <th className={styles.th}>{t('simulation.thSales')}</th>
                    <th className={styles.th}>{t('simulation.thAchievement')}</th>
                    <th className={styles.th}>{t('simulation.thCommission')}</th>
                    <th className={styles.th}>{t('simulation.thAdjustment')}</th>
                    <th className={styles.th}>{t('simulation.thPayout')}</th>
                    <th className={styles.th}>{t('simulation.thAiAudit')}</th>
                    <th className={styles.th}>{t('simulation.thStatus')}</th>
                  </tr>
                </thead>
                <tbody>
                  {results.map((item, idx) => {
                    const colab = usersMap[item.main.userId] || { username: `ID: ${item.main.userId}` };
                    const plan = plansMap[item.main.planId] || { name: `ID: ${item.main.planId}`, version: 1 };
                    const achievementVal = (item.main.achievementPercentage * 100).toFixed(1) + '%';
                    const mainCommission = item.main.calculatedCommission + item.main.calculatedBonus;

                    return (
                      <tr key={idx} className={styles.tr}>
                        <td className={styles.td}>
                          <strong>{colab.username}</strong>
                          {colab.hotel && <div style={{ fontSize: '0.85rem', color: '#94a3b8' }}>{colab.hotel.code}</div>}
                        </td>
                        <td className={styles.td}>
                          {plan.name} (v{plan.version})
                        </td>
                        <td className={styles.td}>
                          ${parseFloat(item.main.goalAmount.toString()).toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                        </td>
                        <td className={styles.td}>
                          ${parseFloat(item.main.salesAmount.toString()).toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                        </td>
                        <td className={styles.td}>{achievementVal}</td>
                        <td className={styles.td}>
                          ${mainCommission.toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                        </td>
                        <td className={`${styles.td} ${item.main.adjustmentAmount < 0 ? styles.negative : item.main.adjustmentAmount > 0 ? styles.positive : ''}`}>
                          ${parseFloat(item.main.adjustmentAmount.toString()).toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                        </td>
                        <td className={styles.td}>
                          <strong>
                            ${parseFloat(item.main.totalPayout.toString()).toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                          </strong>
                        </td>
                        <td className={styles.td}>
                          {item.aiAudited ? (
                            <span className={styles.auditWarning} title={item.aiAuditNotes?.[locale] || ''}>
                              ⚠️ {item.aiAuditNotes?.[locale] || 'Warning'}
                            </span>
                          ) : (
                            <span className={styles.auditOk}>✓ OK</span>
                          )}
                        </td>
                        <td className={styles.td}>
                          <span
                            className={`${styles.badge} ${
                              item.main.status === 'SIMULATED'
                                ? styles.badgeSimulated
                                : item.main.status === 'PENDING'
                                ? styles.badgePending
                                : item.main.status === 'APPROVED'
                                ? styles.badgeApproved
                                : styles.badgeRejected
                            }`}
                          >
                             {t('status.' + item.main.status)}
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
