'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 Settlement {
  id: number;
  period: string;
  planId: number;
  userId: number;
  salesAmount: string;
  goalAmount: string;
  achievementPercentage: string;
  calculatedCommission: string;
  calculatedBonus: string;
  adjustmentAmount: string;
  totalPayout: string;
  status: string;
  rejectionReason: string | null;
  colaborador: {
    username: string;
    email: string;
    area: string;
    hotel: {
      name: string;
      code: string;
    };
  };
  plan: {
    name: string;
    code: string;
    version: number;
  };
}

export default function ApprovalsPage() {
  const router = useRouter();
  const { t } = useLocale();
  const { role, user: currentUser, isLoading: contextLoading } = useUser();
  const [isLoading, setIsLoading] = useState(true);
  const [settlements, setSettlements] = useState<Settlement[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Modal State
  const [showRejectModal, setShowRejectModal] = useState(false);
  const [rejectId, setRejectId] = useState<number | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [isSubmittingReject, setIsSubmittingReject] = useState(false);

  const fetchSettlements = async () => {
    try {
      const res = await fetch('/api/settlements');
      if (res.ok) {
        const data = await res.json();
        setSettlements(data.settlements || []);
      } else {
        const data = await res.json();
        setError(data.error || 'Failed to load settlements.');
      }
    } catch (err) {
      console.error('Failed to fetch settlements:', err);
      setError('Failed to connect to the server.');
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleApprove = async (id: number) => {
    setError(null);
    setSuccess(null);
    try {
      const res = await fetch(`/api/settlements/${id}/approve`, {
        method: 'POST'
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Error al aprobar la liquidación.');
        return;
      }
      setSuccess('Liquidación aprobada con éxito.');
      fetchSettlements();
    } catch (err) {
      console.error('Failed to approve settlement:', err);
      setError('Error al comunicarse con el servidor.');
    }
  };

  const openRejectModal = (id: number) => {
    setRejectId(id);
    setRejectReason('');
    setShowRejectModal(true);
  };

  const closeRejectModal = () => {
    setShowRejectModal(false);
    setRejectId(null);
    setRejectReason('');
  };

  const handleRejectConfirm = async () => {
    if (!rejectId) return;
    if (!rejectReason || rejectReason.trim() === '') {
      setError('La razón del rechazo es obligatoria.');
      return;
    }

    setError(null);
    setSuccess(null);
    setIsSubmittingReject(true);

    try {
      const res = await fetch(`/api/settlements/${rejectId}/reject`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason: rejectReason })
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Error al rechazar la liquidación.');
        setIsSubmittingReject(false);
        return;
      }
      setSuccess('Liquidación rechazada.');
      closeRejectModal();
      fetchSettlements();
    } catch (err) {
      console.error('Failed to reject settlement:', err);
      setError('Error al comunicarse con el servidor.');
    } finally {
      setIsSubmittingReject(false);
    }
  };

  if (isLoading) {
    return (
      <div className={styles.container}>
        <Header activeTab="approvals" />
        <div className={styles.mainContent}>
          <p>Cargando panel de aprobaciones...</p>
        </div>
      </div>
    );
  }

  const isLeader = role === 'commercial_leader';

  return (
    <div className={styles.container}>
      <Header activeTab="approvals" />
      <main className={styles.mainContent}>
        <div className={styles.titleSection}>
          <h1 className={styles.title}>Panel de Aprobaciones</h1>
          <p className={styles.description}>
            {isLeader
              ? 'Revise y apruebe las liquidaciones de comisión de los colaboradores de su región.'
              : 'Visualice y audite el estado de aprobación de las liquidaciones de comisiones.'}
          </p>
        </div>

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

        <div className={styles.card}>
          <div className={styles.tableWrapper}>
            <table className={styles.table} id="approvals-table">
              <thead>
                <tr>
                  <th className={styles.th}>Colaborador</th>
                  <th className={styles.th}>Plan</th>
                  <th className={styles.th}>Período</th>
                  <th className={styles.th}>Meta</th>
                  <th className={styles.th}>Ventas</th>
                  <th className={styles.th}>Cumplimiento</th>
                  <th className={styles.th}>Pago Total</th>
                  <th className={styles.th}>Estado</th>
                  <th className={styles.th}>Acciones</th>
                </tr>
              </thead>
              <tbody>
                {settlements.length === 0 ? (
                  <tr>
                    <td colSpan={9} className={styles.td} style={{ textAlign: 'center' }}>
                      No se encontraron liquidaciones pendientes en su región.
                    </td>
                  </tr>
                ) : (
                  settlements.map((s) => {
                    const achievementVal = (parseFloat(s.achievementPercentage) * 100).toFixed(1) + '%';
                    const isPending = s.status === 'PENDING' || s.status === 'SIMULATED';

                    return (
                      <tr key={s.id} className={styles.tr}>
                        <td className={styles.td}>
                          <strong>{s.colaborador.username}</strong>
                          <div style={{ fontSize: '0.85rem', color: '#94a3b8' }}>
                            {s.colaborador.hotel.name} ({s.colaborador.hotel.code})
                          </div>
                        </td>
                        <td className={styles.td}>
                          {s.plan.name} (v{s.plan.version})
                        </td>
                        <td className={styles.td}>{s.period}</td>
                        <td className={styles.td}>
                          ${parseFloat(s.goalAmount).toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                        </td>
                        <td className={styles.td}>
                          ${parseFloat(s.salesAmount).toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                        </td>
                        <td className={styles.td}>{achievementVal}</td>
                        <td className={styles.td}>
                          <strong>
                            ${parseFloat(s.totalPayout).toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                          </strong>
                        </td>
                        <td className={styles.td}>
                          <span
                            className={`${styles.badge} ${
                              s.status === 'SIMULATED'
                                ? styles.badgeSimulated
                                : s.status === 'PENDING'
                                ? styles.badgePending
                                : s.status === 'APPROVED'
                                ? styles.badgeApproved
                                : styles.badgeRejected
                            }`}
                          >
                            {t('status.' + s.status)}
                          </span>
                          {s.rejectionReason && (
                            <div style={{ fontSize: '0.75rem', color: '#f87171', marginTop: '0.25rem' }}>
                              Razón: {s.rejectionReason}
                            </div>
                          )}
                        </td>
                        <td className={styles.td}>
                          {isPending && (role === 'commercial_leader' || role === 'admin') ? (
                            <div className={styles.actionsCell}>
                              <button
                                id={`btn-approve-${s.id}`}
                                className={styles.btnApprove}
                                onClick={() => handleApprove(s.id)}
                              >
                                Aprobar
                              </button>
                              <button
                                id={`btn-reject-${s.id}`}
                                className={styles.btnReject}
                                onClick={() => openRejectModal(s.id)}
                              >
                                Rechazar
                              </button>
                            </div>
                          ) : (
                            <span style={{ fontSize: '0.85rem', color: '#64748b' }}>Sin acciones</span>
                          )}
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </div>
      </main>

      {showRejectModal && (
        <div className={styles.modalBackdrop}>
          <div className={styles.modalContent}>
            <h2 className={styles.modalTitle}>Rechazar Liquidación</h2>
            <textarea
              id="reject-reason-input"
              className={styles.textarea}
              placeholder="Ingrese el motivo del rechazo..."
              value={rejectReason}
              onChange={(e) => setRejectReason(e.target.value)}
              disabled={isSubmittingReject}
            />
            <div className={styles.modalActions}>
              <button
                id="btn-cancel-reject"
                className={styles.btnCancel}
                onClick={closeRejectModal}
                disabled={isSubmittingReject}
              >
                Cancelar
              </button>
              <button
                id="btn-confirm-reject"
                className={styles.btnConfirmReject}
                onClick={handleRejectConfirm}
                disabled={isSubmittingReject}
              >
                {isSubmittingReject ? 'Rechazando...' : 'Confirmar Rechazo'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
