'use strict';
'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import styles from './page.module.css';
import Header from '@/components/Header';
import { getRoleBilingualLabel } from '@/lib/roles';
import { useLocale } from '@/lib/i18n/LocaleContext';

interface User {
  id: number;
  username: string;
  email: string;
  role: string;
  area: string;
  hotel?: {
    name: string;
    code: string;
  };
}

interface Goal {
  id: number;
  targetType: string;
  targetId: number;
  period: string;
  amount: string; // Decimal comes as string from database
  createdAt: string;
}

export default function GoalsPage() {
  const router = useRouter();
  const { t } = useLocale();
  const [users, setUsers] = useState<User[]>([]);
  const [goals, setGoals] = useState<Goal[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [role, setRole] = useState<string | null>(null);

  // Form State
  const [targetType, setTargetType] = useState('INDIVIDUAL');
  const [targetId, setTargetId] = useState('');
  const [period, setPeriod] = useState('');
  const [amount, setAmount] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const fetchUsersAndGoals = async () => {
    try {
      const [usersRes, goalsRes] = await Promise.all([
        fetch('/api/users'),
        fetch('/api/goals')
      ]);

      if (usersRes.ok) {
        const usersData = await usersRes.json();
        setUsers(usersData.users || []);
        if (usersData.users && usersData.users.length > 0) {
          setTargetId(usersData.users[0].id.toString());
        }
      }
      if (goalsRes.ok) {
        const goalsData = await goalsRes.json();
        setGoals(goalsData.goals || []);
      }
    } catch (err) {
      console.error('Failed to load goals or users:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetch('/api/auth/me')
      .then(res => res.ok ? res.json() : null)
      .then(data => {
        if (data?.user) setRole(data.user.role);
      })
      .catch(err => console.error('Failed to fetch user role', err));
    fetchUsersAndGoals();
  }, []);



  const handleAssignGoal = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSuccess(null);

    if (!targetType || !targetId || !period || !amount) {
      setError('Todos los campos son obligatorios.');
      return;
    }

    const numericAmount = parseFloat(amount);
    if (isNaN(numericAmount) || numericAmount <= 0) {
      setError('El monto debe ser un número positivo.');
      return;
    }

    try {
      const res = await fetch('/api/goals', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          targetType,
          targetId: parseInt(targetId),
          period,
          amount: numericAmount
        })
      });

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Error al asignar la meta.');
        return;
      }

      setSuccess('Meta comercial asignada / actualizada exitosamente.');
      setAmount('');
      // Reload goals list
      const goalsRes = await fetch('/api/goals');
      if (goalsRes.ok) {
        const goalsData = await goalsRes.json();
        setGoals(goalsData.goals || []);
      }
    } catch (err) {
      setError('Ocurrió un error al guardar la meta.');
    }
  };

  const getTargetLabel = (type: string, id: number) => {
    if (type === 'INDIVIDUAL') {
      const user = users.find(u => u.id === id);
      if (user) {
        return `${user.username} (${getRoleBilingualLabel(user.role)} - ${user.hotel?.name || ''})`;
      }
    }
    return `${type} ID: ${id}`;
  };

  return (
    <div className={styles.container}>
      {/* Shared Dashboard Header */}
      <Header activeTab="goals" />

      <main className={styles.main}>
        <div className={styles.titleSection}>
          <h1 className={styles.title}>Metas Comerciales</h1>
        </div>

        {/* Goal Assignment Form Section */}
        {(role === 'admin' || role === 'director') && (
          <section className={styles.section}>
            <h2 className={styles.sectionTitle}>Asignar Meta</h2>
            {error && <div className={styles.errorMsg} id="goal-error-msg">{error}</div>}
            {success && <div className={styles.successMsg} id="goal-success-msg">{success}</div>}

            <form onSubmit={handleAssignGoal} className={styles.form}>
              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="goal-target-type">Tipo de Meta</label>
                <select
                  id="goal-target-type"
                  className={styles.input}
                  value={targetType}
                  onChange={(e) => setTargetType(e.target.value)}
                >
                  <option value="INDIVIDUAL">Colaborador Individual</option>
                  <option value="TEAM">Equipo</option>
                  <option value="HOTEL">Hotel</option>
                </select>
              </div>

              {targetType === 'INDIVIDUAL' && (
                <div className={styles.formGroup}>
                  <label className={styles.label} htmlFor="goal-target-id">Seleccionar Colaborador</label>
                  <select
                    id="goal-target-id"
                    className={styles.input}
                    value={targetId}
                    onChange={(e) => setTargetId(e.target.value)}
                    required
                  >
                    {users.map((u) => (
                      <option key={u.id} value={u.id}>
                        {u.username} ({getRoleBilingualLabel(u.role)} - {u.hotel?.code})
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {targetType !== 'INDIVIDUAL' && (
                <div className={styles.formGroup}>
                  <label className={styles.label} htmlFor="goal-target-id-input">ID del Objetivo (Hotel/Equipo)</label>
                  <input
                    id="goal-target-id-input"
                    type="number"
                    className={styles.input}
                    value={targetId}
                    onChange={(e) => setTargetId(e.target.value)}
                    placeholder="Ej. ID de Hotel o Equipo"
                    required
                  />
                </div>
              )}

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="goal-period">Período (Mes/Año)</label>
                <input
                  id="goal-period"
                  type="month"
                  className={styles.input}
                  value={period}
                  onChange={(e) => setPeriod(e.target.value)}
                  required
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="goal-amount">Monto Quota ($)</label>
                <input
                  id="goal-amount"
                  type="number"
                  step="0.01"
                  className={styles.input}
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  placeholder="Ej. 50000.00"
                  required
                />
              </div>

              <button type="submit" className={styles.btnPrimary} id="btn-save-goal">
                Asignar Meta
              </button>
            </form>
          </section>
        )}

        {/* Configured Goals List Section */}
        <section className={`${styles.section} ${!(role === 'admin' || role === 'director') ? styles.fullWidth : ''}`}>
          <h2 className={styles.sectionTitle}>Historial de Metas</h2>
          {isLoading ? (
            <div style={{ textAlign: 'center', padding: '20px' }}>Cargando metas...</div>
          ) : (
            <div className={styles.tableContainer}>
              <table className={styles.table}>
                <thead>
                  <tr>
                    <th className={styles.th}>Objetivo</th>
                    <th className={styles.th}>Período</th>
                    <th className={styles.th}>Tipo</th>
                    <th className={styles.th}>Cuota ($)</th>
                  </tr>
                </thead>
                <tbody>
                  {goals.length === 0 ? (
                    <tr>
                      <td colSpan={4} className={styles.emptyState}>No hay metas configuradas.</td>
                    </tr>
                  ) : (
                    goals.map((g) => (
                      <tr key={g.id} data-goal-row-id={g.id}>
                        <td className={styles.td}>{getTargetLabel(g.targetType, g.targetId)}</td>
                        <td className={styles.td}>{g.period}</td>
                        <td className={styles.td}>
                          <span className={`${styles.badge} ${styles['badge' + g.targetType]}`}>
                            {t('targetType.' + g.targetType)}
                          </span>
                        </td>
                        <td className={styles.td} style={{ fontWeight: 'bold' }}>
                          ${parseFloat(g.amount).toLocaleString('es-CO', { minimumFractionDigits: 2 })}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          )}
        </section>
      </main>
    </div>
  );
}
