'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 { useLocale } from '@/lib/i18n/LocaleContext';

interface Plan {
  id: number;
  name: string;
  code: string;
  validityStart: string;
  validityEnd: string | null;
  type: string;
  formula: string | null;
  metaAmount: number | null;
  percentageRate: number | null;
  maxCap: number | null;
  status: string;
  version: number;
  rules: any[];
}

export default function PlansPage() {
  const router = useRouter();
  const { t } = useLocale();
  const [plans, setPlans] = useState<Plan[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [role, setRole] = useState<string | null>(null);

  // Form State
  const [name, setName] = useState('');
  const [code, setCode] = useState('');
  const [validityStart, setValidityStart] = useState('');
  const [type, setType] = useState('PERCENTAGE');
  const [metaAmount, setMetaAmount] = useState('');
  const [percentageRate, setPercentageRate] = useState('');
  const [maxCap, setMaxCap] = useState('');
  const [status, setStatus] = useState('DRAFT');
  const [error, setError] = useState<string | null>(null);

  const fetchPlans = async () => {
    try {
      const res = await fetch('/api/plans');
      if (res.ok) {
        const data = await res.json();
        setPlans(data.plans || []);
      }
    } catch (err) {
      console.error('Failed to fetch plans', 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));
    fetchPlans();
  }, []);



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

    if (!name || !code || !validityStart || !type) {
      setError('Name, code, validityStart, and type are required fields');
      return;
    }

    try {
      const res = await fetch('/api/plans', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name,
          code,
          validityStart,
          type,
          metaAmount: metaAmount ? parseFloat(metaAmount) : undefined,
          percentageRate: percentageRate ? parseFloat(percentageRate) : undefined,
          maxCap: maxCap ? parseFloat(maxCap) : undefined,
          status
        })
      });

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || 'Failed to create plan');
        return;
      }

      // Reset form & reload
      setName('');
      setCode('');
      setValidityStart('');
      setType('PERCENTAGE');
      setMetaAmount('');
      setPercentageRate('');
      setMaxCap('');
      setStatus('DRAFT');
      setShowModal(false);
      fetchPlans();
    } catch (err) {
      setError('An error occurred during submission.');
    }
  };

  const handleToggleStatus = async (plan: Plan) => {
    const nextStatus = plan.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
    try {
      const res = await fetch(`/api/plans/${plan.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          status: nextStatus
        })
      });

      if (res.ok) {
        fetchPlans();
      }
    } catch (err) {
      console.error('Failed to toggle status', err);
    }
  };

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

      <main className={styles.main}>
        <div className={styles.titleSection}>
          <h1 className={styles.title}>Planes de Comisión</h1>
          {(role === 'admin' || role === 'director') && (
            <button onClick={() => setShowModal(true)} className={styles.btnPrimary} id="btn-create-plan">
              Nuevo Plan
            </button>
          )}
        </div>

        {isLoading ? (
          <div className={styles.loading}>Cargando planes...</div>
        ) : (
          <div className={styles.grid}>
            {plans.map((plan) => (
              <div key={plan.id} className={styles.card} data-plan-id={plan.id}>
                <div>
                  <div className={styles.cardHeader}>
                    <span className={styles.cardCode}>{plan.code}</span>
                    <span className={`${styles.badge} ${styles['badge' + plan.status]}`}>
                      {t('status.' + plan.status)}
                    </span>
                  </div>
                  <h2 className={styles.cardTitle}>{plan.name}</h2>
                  <div className={styles.cardMeta}>
                    <div className={styles.metaItem}>
                      <span>Versión:</span>
                      <span className={styles.metaValue} data-version-id={plan.id}>{plan.version}</span>
                    </div>
                    <div className={styles.metaItem}>
                      <span>Inicio Vigencia:</span>
                      <span className={styles.metaValue}>
                        {new Date(plan.validityStart).toLocaleDateString()}
                      </span>
                    </div>
                    {plan.validityEnd && (
                      <div className={styles.metaItem}>
                        <span>Fin Vigencia:</span>
                        <span className={styles.metaValue}>
                          {new Date(plan.validityEnd).toLocaleDateString()}
                        </span>
                      </div>
                    )}
                    <div className={styles.metaItem}>
                      <span>Reglas creadas:</span>
                      <span className={styles.metaValue}>{plan.rules ? plan.rules.length : 0}</span>
                    </div>
                  </div>
                </div>

                <div className={styles.cardFooter}>
                  { (role === 'admin' || role === 'director') ? (
                    <>
                      <Link href={`/plans/${plan.id}/rules`} className={styles.btnSecondary} id={`btn-rules-${plan.id}`}>
                        Configurar Reglas
                      </Link>
                      <button
                        onClick={() => handleToggleStatus(plan)}
                        className={styles.btnSecondary}
                        id={`btn-toggle-status-${plan.id}`}
                      >
                        {plan.status === 'ACTIVE' ? 'Inactivar (Versión)' : 'Activar'}
                      </button>
                    </>
                  ) : (
                    <Link href={`/plans/${plan.id}/rules`} className={styles.btnSecondary} id={`btn-rules-${plan.id}`}>
                      Ver Reglas
                    </Link>
                  ) }
                </div>
              </div>
            ))}
          </div>
        )}
      </main>

      {/* Creation Modal */}
      {showModal && (
        <div className={styles.modalOverlay} role="dialog">
          <div className={styles.modal}>
            <h2 className={styles.modalTitle}>Crear Nuevo Plan</h2>
            <form onSubmit={handleCreatePlan} className={styles.form}>
              {error && <div className={styles.errorText}>{error}</div>}

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="plan-name">Nombre del Plan</label>
                <input
                  id="plan-name"
                  type="text"
                  required
                  className={styles.input}
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Ej. Plan Comercial Bogotá"
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="plan-code">Código del Plan</label>
                <input
                  id="plan-code"
                  type="text"
                  required
                  className={styles.input}
                  value={code}
                  onChange={(e) => setCode(e.target.value)}
                  placeholder="Ej. PLAN-BOG-2026"
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="plan-validity-start">Inicio de Vigencia</label>
                <input
                  id="plan-validity-start"
                  type="date"
                  required
                  className={styles.input}
                  value={validityStart}
                  onChange={(e) => setValidityStart(e.target.value)}
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="plan-type">Tipo de Remuneración</label>
                <select
                  id="plan-type"
                  className={styles.input}
                  value={type}
                  onChange={(e) => setType(e.target.value)}
                >
                  <option value="PERCENTAGE">Porcentaje Simple</option>
                  <option value="SCALE">Escala Contigua</option>
                  <option value="CONDITIONAL">Condicional por Metas</option>
                  <option value="FIXED">Comisión Fija</option>
                </select>
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="plan-meta-amount">Meta de Ventas (Opcional)</label>
                <input
                  id="plan-meta-amount"
                  type="number"
                  step="0.01"
                  className={styles.input}
                  value={metaAmount}
                  onChange={(e) => setMetaAmount(e.target.value)}
                  placeholder="Ej. 100000.00"
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="plan-max-cap">Tope Máximo / Cap (Opcional)</label>
                <input
                  id="plan-max-cap"
                  type="number"
                  step="0.01"
                  className={styles.input}
                  value={maxCap}
                  onChange={(e) => setMaxCap(e.target.value)}
                  placeholder="Ej. 15000.00"
                />
              </div>

              <div className={styles.formGroup}>
                <label className={styles.label} htmlFor="plan-status">Estado Inicial</label>
                <select
                  id="plan-status"
                  className={styles.input}
                  value={status}
                  onChange={(e) => setStatus(e.target.value)}
                >
                  <option value="DRAFT">{t('status.DRAFT')}</option>
                  <option value="ACTIVE">{t('status.ACTIVE')}</option>
                </select>
              </div>

              <div className={styles.formActions}>
                <button type="button" onClick={() => setShowModal(false)} className={styles.btnSecondary}>
                  Cancelar
                </button>
                <button type="submit" className={styles.btnPrimary} id="btn-save-plan">
                  Guardar Plan
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
