import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { financialGoalService } from '../services/api';
import useFormatters from '../hooks/useFormatters';
import ConfirmModal from '../components/ConfirmModal';

const Goals = () => {
  const { t } = useTranslation();
  const { currency, formatDate } = useFormatters();
  
  const [loading, setLoading] = useState(true);
  const [goals, setGoals] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [showContributeModal, setShowContributeModal] = useState(false);
  const [editingGoal, setEditingGoal] = useState(null);
  const [contributingGoal, setContributingGoal] = useState(null);
  const [deleteGoal, setDeleteGoal] = useState(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    target_amount: '',
    current_amount: '',
    target_date: '',
    monthly_contribution: '',
    color: '#3b82f6',
    icon: 'bi-piggy-bank',
  });
  const [contributeAmount, setContributeAmount] = useState('');
  const [contributeNote, setContributeNote] = useState('');

  const icons = [
    'bi-piggy-bank', 'bi-house', 'bi-car-front', 'bi-airplane', 'bi-laptop',
    'bi-phone', 'bi-gift', 'bi-mortarboard', 'bi-heart', 'bi-gem',
    'bi-currency-dollar', 'bi-wallet2', 'bi-safe', 'bi-shield-check', 'bi-lightning',
  ];

  const colors = [
    '#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6',
    '#ec4899', '#06b6d4', '#84cc16', '#f97316', '#6366f1',
  ];

  useEffect(() => {
    loadGoals();
  }, []);

  const loadGoals = async () => {
    setLoading(true);
    try {
      const data = await financialGoalService.getAll();
      setGoals(data);
    } catch (error) {
      console.error('Error loading goals:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingGoal) {
        await financialGoalService.update(editingGoal.id, formData);
      } else {
        await financialGoalService.create(formData);
      }
      setShowModal(false);
      setEditingGoal(null);
      resetForm();
      loadGoals();
    } catch (error) {
      console.error('Error saving goal:', error);
    }
  };

  const handleContribute = async (e) => {
    e.preventDefault();
    if (!contributingGoal || !contributeAmount) return;

    try {
      await financialGoalService.addContribution(contributingGoal.id, {
        amount: parseFloat(contributeAmount),
        notes: contributeNote || null,
      });
      setShowContributeModal(false);
      setContributingGoal(null);
      setContributeAmount('');
      setContributeNote('');
      loadGoals();
    } catch (error) {
      console.error('Error adding contribution:', error);
    }
  };

  const handleDelete = async () => {
    if (!deleteGoal) return;
    try {
      await financialGoalService.delete(deleteGoal.id);
      setDeleteGoal(null);
      loadGoals();
    } catch (error) {
      console.error('Error deleting goal:', error);
    }
  };

  const handleEdit = (goal) => {
    setEditingGoal(goal);
    setFormData({
      name: goal.name,
      description: goal.description || '',
      target_amount: goal.target_amount,
      current_amount: goal.current_amount,
      target_date: goal.target_date || '',
      monthly_contribution: goal.monthly_contribution || '',
      color: goal.color || '#3b82f6',
      icon: goal.icon || 'bi-piggy-bank',
    });
    setShowModal(true);
  };

  const handleStatusChange = async (goal, status) => {
    try {
      await financialGoalService.update(goal.id, { ...goal, status });
      loadGoals();
    } catch (error) {
      console.error('Error updating status:', error);
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      description: '',
      target_amount: '',
      current_amount: '',
      target_date: '',
      monthly_contribution: '',
      color: '#3b82f6',
      icon: 'bi-piggy-bank',
    });
  };

  const openNewGoal = () => {
    setEditingGoal(null);
    resetForm();
    setShowModal(true);
  };

  const getStatusBadge = (status) => {
    const statusConfig = {
      active: { bg: 'bg-primary', label: t('goals.statusActive') },
      completed: { bg: 'bg-success', label: t('goals.statusCompleted') },
      paused: { bg: 'bg-warning', label: t('goals.statusPaused') },
      cancelled: { bg: 'bg-secondary', label: t('goals.statusCancelled') },
    };
    const config = statusConfig[status] || statusConfig.active;
    return <span className={`badge ${config.bg}`}>{config.label}</span>;
  };

  // Stats calculation
  const stats = {
    total: goals.length,
    active: goals.filter(g => g.status === 'active').length,
    completed: goals.filter(g => g.status === 'completed').length,
    totalTarget: goals.reduce((sum, g) => sum + parseFloat(g.target_amount), 0),
    totalCurrent: goals.reduce((sum, g) => sum + parseFloat(g.current_amount), 0),
  };

  if (loading) {
    return (
      <div className="d-flex justify-content-center align-items-center" style={{ minHeight: '400px' }}>
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">{t('common.loading')}</span>
        </div>
      </div>
    );
  }

  return (
    <div className="goals-container">
      {/* Header */}
      <div className="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h4 className="text-white mb-1 fw-bold">
            <i className="bi bi-flag me-2"></i>
            {t('goals.title')}
          </h4>
          <p className="text-slate-400 mb-0 small">{t('goals.subtitle')}</p>
        </div>
        <button className="btn btn-primary" onClick={openNewGoal}>
          <i className="bi bi-plus-lg me-1"></i>
          {t('goals.addGoal')}
        </button>
      </div>

      {/* Stats Cards */}
      <div className="row g-3 mb-4">
        <div className="col-md-3">
          <div className="card border-0" style={{ background: '#1e293b' }}>
            <div className="card-body text-center py-3">
              <small className="text-slate-400">{t('goals.totalGoals')}</small>
              <h4 className="text-white mb-0">{stats.total}</h4>
            </div>
          </div>
        </div>
        <div className="col-md-3">
          <div className="card border-0" style={{ background: '#1e293b' }}>
            <div className="card-body text-center py-3">
              <small className="text-slate-400">{t('goals.activeGoals')}</small>
              <h4 className="text-primary mb-0">{stats.active}</h4>
            </div>
          </div>
        </div>
        <div className="col-md-3">
          <div className="card border-0" style={{ background: '#1e293b' }}>
            <div className="card-body text-center py-3">
              <small className="text-slate-400">{t('goals.totalSaved')}</small>
              <h4 className="text-success mb-0">{currency(stats.totalCurrent)}</h4>
            </div>
          </div>
        </div>
        <div className="col-md-3">
          <div className="card border-0" style={{ background: '#1e293b' }}>
            <div className="card-body text-center py-3">
              <small className="text-slate-400">{t('goals.remaining')}</small>
              <h4 className="text-warning mb-0">{currency(stats.totalTarget - stats.totalCurrent)}</h4>
            </div>
          </div>
        </div>
      </div>

      {/* Goals Grid */}
      {goals.length === 0 ? (
        <div className="card border-0 text-center py-5" style={{ background: '#0f172a' }}>
          <div className="card-body">
            <i className="bi bi-flag text-slate-500" style={{ fontSize: '4rem' }}></i>
            <h5 className="text-white mt-3">{t('goals.noGoals')}</h5>
            <p className="text-slate-400">{t('goals.noGoalsDescription')}</p>
            <button className="btn btn-primary" onClick={openNewGoal}>
              <i className="bi bi-plus-lg me-1"></i>
              {t('goals.createFirstGoal')}
            </button>
          </div>
        </div>
      ) : (
        <div className="row g-4">
          {goals.map(goal => {
            const progress = goal.progress_percentage || 
              ((goal.current_amount / goal.target_amount) * 100);
            const remaining = goal.remaining_amount || 
              (goal.target_amount - goal.current_amount);

            return (
              <div key={goal.id} className="col-md-6 col-lg-4">
                <div 
                  className="card border-0 h-100" 
                  style={{ 
                    background: '#0f172a',
                    borderTop: `3px solid ${goal.color || '#3b82f6'}`
                  }}
                >
                  <div className="card-body">
                    {/* Header */}
                    <div className="d-flex align-items-start justify-content-between mb-3">
                      <div className="d-flex align-items-center">
                        <div 
                          className="rounded-circle p-2 me-2"
                          style={{ background: `${goal.color || '#3b82f6'}20` }}
                        >
                          <i 
                            className={`bi ${goal.icon || 'bi-piggy-bank'} fs-5`}
                            style={{ color: goal.color || '#3b82f6' }}
                          ></i>
                        </div>
                        <div>
                          <h6 className="text-white mb-0">{goal.name}</h6>
                          {goal.description && (
                            <small className="text-slate-400">{goal.description}</small>
                          )}
                        </div>
                      </div>
                      {getStatusBadge(goal.status)}
                    </div>

                    {/* Progress */}
                    <div className="mb-3">
                      <div className="d-flex justify-content-between mb-1">
                        <span className="text-success fw-bold">{currency(goal.current_amount)}</span>
                        <span className="text-slate-400">{currency(goal.target_amount)}</span>
                      </div>
                      <div className="progress bg-slate-700" style={{ height: '8px' }}>
                        <div 
                          className="progress-bar"
                          style={{ 
                            width: `${Math.min(progress, 100)}%`,
                            background: goal.color || '#3b82f6'
                          }}
                        ></div>
                      </div>
                      <div className="d-flex justify-content-between mt-1">
                        <small className="text-slate-400">{progress.toFixed(1)}%</small>
                        <small className="text-slate-400">
                          {t('goals.remaining')}: {currency(remaining)}
                        </small>
                      </div>
                    </div>

                    {/* Info */}
                    <div className="mb-3">
                      {goal.target_date && (
                        <div className="d-flex justify-content-between small mb-1">
                          <span className="text-slate-400">{t('goals.targetDate')}</span>
                          <span className="text-white">{formatDate(goal.target_date)}</span>
                        </div>
                      )}
                      {goal.monthly_contribution > 0 && (
                        <div className="d-flex justify-content-between small mb-1">
                          <span className="text-slate-400">{t('goals.monthlyContribution')}</span>
                          <span className="text-white">{currency(goal.monthly_contribution)}</span>
                        </div>
                      )}
                      {goal.months_remaining > 0 && (
                        <div className="d-flex justify-content-between small">
                          <span className="text-slate-400">{t('goals.monthsRemaining')}</span>
                          <span className="text-white">{goal.months_remaining} {t('goals.months')}</span>
                        </div>
                      )}
                    </div>

                    {/* On Track Indicator */}
                    {goal.status === 'active' && goal.is_on_track !== undefined && (
                      <div className={`alert ${goal.is_on_track ? 'alert-success' : 'alert-warning'} py-2 mb-3`}>
                        <small>
                          <i className={`bi ${goal.is_on_track ? 'bi-check-circle' : 'bi-exclamation-triangle'} me-1`}></i>
                          {goal.is_on_track 
                            ? t('goals.onTrack')
                            : t('goals.needsMore', { amount: currency(goal.required_monthly_saving || 0) })
                          }
                        </small>
                      </div>
                    )}

                    {/* Actions */}
                    <div className="d-flex gap-2">
                      {goal.status === 'active' && (
                        <button 
                          className="btn btn-primary btn-sm flex-grow-1"
                          onClick={() => {
                            setContributingGoal(goal);
                            setShowContributeModal(true);
                          }}
                        >
                          <i className="bi bi-plus-circle me-1"></i>
                          {t('goals.contribute')}
                        </button>
                      )}
                      <button 
                        className="btn btn-outline-secondary btn-sm"
                        onClick={() => handleEdit(goal)}
                      >
                        <i className="bi bi-pencil"></i>
                      </button>
                      <div className="dropdown">
                        <button 
                          className="btn btn-outline-secondary btn-sm dropdown-toggle"
                          data-bs-toggle="dropdown"
                        >
                          <i className="bi bi-three-dots-vertical"></i>
                        </button>
                        <ul className="dropdown-menu dropdown-menu-dark dropdown-menu-end">
                          {goal.status === 'active' && (
                            <li>
                              <button 
                                className="dropdown-item"
                                onClick={() => handleStatusChange(goal, 'paused')}
                              >
                                <i className="bi bi-pause-circle me-2"></i>
                                {t('goals.pause')}
                              </button>
                            </li>
                          )}
                          {goal.status === 'paused' && (
                            <li>
                              <button 
                                className="dropdown-item"
                                onClick={() => handleStatusChange(goal, 'active')}
                              >
                                <i className="bi bi-play-circle me-2"></i>
                                {t('goals.resume')}
                              </button>
                            </li>
                          )}
                          {goal.status !== 'completed' && (
                            <li>
                              <button 
                                className="dropdown-item text-success"
                                onClick={() => handleStatusChange(goal, 'completed')}
                              >
                                <i className="bi bi-check-circle me-2"></i>
                                {t('goals.markCompleted')}
                              </button>
                            </li>
                          )}
                          <li><hr className="dropdown-divider" /></li>
                          <li>
                            <button 
                              className="dropdown-item text-danger"
                              onClick={() => setDeleteGoal(goal)}
                            >
                              <i className="bi bi-trash me-2"></i>
                              {t('common.delete')}
                            </button>
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Goal Form Modal */}
      {showModal && (
        <div className="modal show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.7)' }}>
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content border-0" style={{ background: '#1e293b' }}>
              <div className="modal-header border-0">
                <h5 className="modal-title text-white">
                  <i className={`bi ${editingGoal ? 'bi-pencil' : 'bi-plus-circle'} me-2`}></i>
                  {editingGoal ? t('goals.editGoal') : t('goals.newGoal')}
                </h5>
                <button 
                  type="button" 
                  className="btn-close btn-close-white" 
                  onClick={() => setShowModal(false)}
                ></button>
              </div>
              <form onSubmit={handleSubmit}>
                <div className="modal-body">
                  {/* Name */}
                  <div className="mb-3">
                    <label className="form-label text-slate-400">{t('goals.name')} *</label>
                    <input
                      type="text"
                      className="form-control bg-dark border-secondary text-white"
                      value={formData.name}
                      onChange={(e) => setFormData({...formData, name: e.target.value})}
                      required
                    />
                  </div>

                  {/* Description */}
                  <div className="mb-3">
                    <label className="form-label text-slate-400">{t('goals.description')}</label>
                    <textarea
                      className="form-control bg-dark border-secondary text-white"
                      rows="2"
                      value={formData.description}
                      onChange={(e) => setFormData({...formData, description: e.target.value})}
                    ></textarea>
                  </div>

                  {/* Target Amount */}
                  <div className="row mb-3">
                    <div className="col-6">
                      <label className="form-label text-slate-400">{t('goals.targetAmount')} *</label>
                      <input
                        type="number"
                        step="0.01"
                        className="form-control bg-dark border-secondary text-white"
                        value={formData.target_amount}
                        onChange={(e) => setFormData({...formData, target_amount: e.target.value})}
                        required
                      />
                    </div>
                    <div className="col-6">
                      <label className="form-label text-slate-400">{t('goals.currentAmount')}</label>
                      <input
                        type="number"
                        step="0.01"
                        className="form-control bg-dark border-secondary text-white"
                        value={formData.current_amount}
                        onChange={(e) => setFormData({...formData, current_amount: e.target.value})}
                      />
                    </div>
                  </div>

                  {/* Target Date & Monthly */}
                  <div className="row mb-3">
                    <div className="col-6">
                      <label className="form-label text-slate-400">{t('goals.targetDate')}</label>
                      <input
                        type="date"
                        className="form-control bg-dark border-secondary text-white"
                        value={formData.target_date}
                        onChange={(e) => setFormData({...formData, target_date: e.target.value})}
                      />
                    </div>
                    <div className="col-6">
                      <label className="form-label text-slate-400">{t('goals.monthlyContribution')}</label>
                      <input
                        type="number"
                        step="0.01"
                        className="form-control bg-dark border-secondary text-white"
                        value={formData.monthly_contribution}
                        onChange={(e) => setFormData({...formData, monthly_contribution: e.target.value})}
                      />
                    </div>
                  </div>

                  {/* Icon Selection */}
                  <div className="mb-3">
                    <label className="form-label text-slate-400">{t('goals.icon')}</label>
                    <div className="d-flex flex-wrap gap-2">
                      {icons.map(icon => (
                        <button
                          key={icon}
                          type="button"
                          className={`btn btn-sm ${formData.icon === icon ? 'btn-primary' : 'btn-outline-secondary'}`}
                          onClick={() => setFormData({...formData, icon})}
                        >
                          <i className={`bi ${icon}`}></i>
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Color Selection */}
                  <div className="mb-3">
                    <label className="form-label text-slate-400">{t('goals.color')}</label>
                    <div className="d-flex flex-wrap gap-2">
                      {colors.map(color => (
                        <button
                          key={color}
                          type="button"
                          className="btn btn-sm p-0"
                          style={{ 
                            width: '32px', 
                            height: '32px', 
                            background: color,
                            borderRadius: '50%',
                            border: formData.color === color ? '3px solid white' : 'none'
                          }}
                          onClick={() => setFormData({...formData, color})}
                        ></button>
                      ))}
                    </div>
                  </div>
                </div>
                <div className="modal-footer border-0">
                  <button 
                    type="button" 
                    className="btn btn-outline-secondary"
                    onClick={() => setShowModal(false)}
                  >
                    {t('common.cancel')}
                  </button>
                  <button type="submit" className="btn btn-primary">
                    <i className="bi bi-check-lg me-1"></i>
                    {t('common.save')}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Contribute Modal */}
      {showContributeModal && contributingGoal && (
        <div className="modal show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.7)' }}>
          <div className="modal-dialog modal-dialog-centered modal-sm">
            <div className="modal-content border-0" style={{ background: '#1e293b' }}>
              <div className="modal-header border-0">
                <h5 className="modal-title text-white">
                  <i className="bi bi-plus-circle me-2"></i>
                  {t('goals.contribute')}
                </h5>
                <button 
                  type="button" 
                  className="btn-close btn-close-white" 
                  onClick={() => setShowContributeModal(false)}
                ></button>
              </div>
              <form onSubmit={handleContribute}>
                <div className="modal-body">
                  <div className="text-center mb-3">
                    <i 
                      className={`bi ${contributingGoal.icon || 'bi-piggy-bank'} fs-1`}
                      style={{ color: contributingGoal.color || '#3b82f6' }}
                    ></i>
                    <h6 className="text-white mt-2">{contributingGoal.name}</h6>
                    <small className="text-slate-400">
                      {currency(contributingGoal.current_amount)} de {currency(contributingGoal.target_amount)}
                    </small>
                  </div>

                  <div className="mb-3">
                    <label className="form-label text-slate-400">{t('goals.contributeAmount')} *</label>
                    <input
                      type="number"
                      step="0.01"
                      className="form-control bg-dark border-secondary text-white text-center fs-4"
                      value={contributeAmount}
                      onChange={(e) => setContributeAmount(e.target.value)}
                      required
                      autoFocus
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label text-slate-400">{t('goals.notes')}</label>
                    <input
                      type="text"
                      className="form-control bg-dark border-secondary text-white"
                      value={contributeNote}
                      onChange={(e) => setContributeNote(e.target.value)}
                      placeholder={t('goals.notesPlaceholder')}
                    />
                  </div>
                </div>
                <div className="modal-footer border-0">
                  <button 
                    type="button" 
                    className="btn btn-outline-secondary"
                    onClick={() => setShowContributeModal(false)}
                  >
                    {t('common.cancel')}
                  </button>
                  <button type="submit" className="btn btn-success">
                    <i className="bi bi-plus-lg me-1"></i>
                    {t('goals.addContribution')}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation */}
      <ConfirmModal
        show={!!deleteGoal}
        onClose={() => setDeleteGoal(null)}
        onConfirm={handleDelete}
        title={t('goals.deleteGoal')}
        message={t('goals.deleteConfirm', { name: deleteGoal?.name })}
        confirmText={t('common.delete')}
        variant="danger"
      />
    </div>
  );
};

export default Goals;
