'use client';

import { useState, useEffect } from 'react';
import { useLanguage } from '@/context/LanguageContext';
import { useAuth } from '@/context/AuthContext';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import { dashboardApi, UserProfile } from '@/lib/api';
import { parseDate } from '@/lib/utils';
import toast from 'react-hot-toast';

interface ProfileTabProps {
  onUpdate?: () => void;
}

export default function ProfileTab({ onUpdate }: ProfileTabProps) {
  const { locale: language } = useLanguage();
  const { updateUser, user } = useAuth();
  
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    languagePreference: '',
    rucNumber: '',
  });

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

  const loadProfile = async () => {
    try {
      const res = await dashboardApi.getProfile();
      setProfile(res.profile);
      setFormData({
        name: res.profile.name || '',
        phone: res.profile.phone || '',
        languagePreference: res.profile.languagePreference || '',
        rucNumber: res.profile.rucNumber || '',
      });
    } catch (error) {
      toast.error(language === 'es' ? 'Error al cargar perfil' : 'Failed to load profile');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);

    try {
      const res = await dashboardApi.updateProfile(formData);
      toast.success(language === 'es' ? 'Perfil actualizado' : 'Profile updated');
      
      // Update auth context
      if (user) {
        updateUser({
          ...user,
          name: formData.name,
          phone: formData.phone,
          languagePreference: formData.languagePreference,
          rucNumber: formData.rucNumber,
        });
      }
      
      if (onUpdate) onUpdate();
    } catch (error: any) {
      toast.error(error.message || (language === 'es' ? 'Error al actualizar' : 'Update failed'));
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-secondary-blue"></div>
      </div>
    );
  }

  return (
    <div className="max-w-2xl space-y-6">
      {/* Account Info Card */}
      <Card className="p-6">
        <h3 className="text-lg font-semibold mb-4">
          {language === 'es' ? 'Información de la Cuenta' : 'Account Information'}
        </h3>
        
        <div className="space-y-3 text-sm">
          <div className="flex justify-between py-2 border-b">
            <span className="text-gray-600">Email</span>
            <span className="font-medium">{profile?.email}</span>
          </div>
          <div className="flex justify-between py-2 border-b">
            <span className="text-gray-600">
              {language === 'es' ? 'Estado de Cuenta' : 'Account Status'}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${
              profile?.accountStatus === 'active'
                ? 'bg-green-100 text-green-800'
                : 'bg-yellow-100 text-yellow-800'
            }`}>
              {profile?.accountStatus === 'active' 
                ? (language === 'es' ? 'Activo' : 'Active')
                : profile?.accountStatus}
            </span>
          </div>
          <div className="flex justify-between py-2 border-b">
            <span className="text-gray-600">
              {language === 'es' ? 'Miembro Desde' : 'Member Since'}
            </span>
            <span className="font-medium">
              {profile?.memberSince
                ? parseDate(profile.memberSince).toLocaleDateString(
                    language === 'es' ? 'es-ES' : 'en-US',
                    { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'America/Asuncion' }
                  )
                : '-'}
            </span>
          </div>
          <div className="flex justify-between py-2">
            <span className="text-gray-600">
              {language === 'es' ? 'Días de Membresía' : 'Membership Days'}
            </span>
            <span className="font-medium">{profile?.membershipDays || 0}</span>
          </div>
        </div>
      </Card>

      {/* Edit Profile Form */}
      <Card className="p-6">
        <h3 className="text-lg font-semibold mb-4">
          {language === 'es' ? 'Editar Perfil' : 'Edit Profile'}
        </h3>
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <Input
            id="name"
            label={language === 'es' ? 'Nombre' : 'Name'}
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            required
          />
          
          <Input
            id="phone"
            label={language === 'es' ? 'Teléfono' : 'Phone'}
            type="tel"
            value={formData.phone}
            onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
          />
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {language === 'es' ? 'Idioma Preferido' : 'Preferred Language'}
            </label>
            <select
              value={formData.languagePreference}
              onChange={(e) => setFormData({ ...formData, languagePreference: e.target.value })}
              className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary-blue"
            >
              <option value="">{language === 'es' ? 'Seleccionar' : 'Select'}</option>
              <option value="en">English</option>
              <option value="es">Español</option>
            </select>
          </div>
          
          <Input
            id="rucNumber"
            label={language === 'es' ? 'Número de RUC (para facturas)' : 'RUC Number (for invoices)'}
            value={formData.rucNumber}
            onChange={(e) => setFormData({ ...formData, rucNumber: e.target.value })}
            placeholder={language === 'es' ? 'Opcional' : 'Optional'}
          />
          <p className="text-xs text-gray-500 -mt-2">
            {language === 'es'
              ? 'Tu número de RUC paraguayo para facturas fiscales'
              : 'Your Paraguayan RUC number for fiscal invoices'}
          </p>
          
          <div className="pt-4">
            <Button type="submit" isLoading={saving}>
              {language === 'es' ? 'Guardar Cambios' : 'Save Changes'}
            </Button>
          </div>
        </form>
      </Card>

      {/* Email Change Notice */}
      <Card className="p-6 bg-gray-50">
        <h3 className="text-lg font-semibold mb-2">
          {language === 'es' ? 'Cambiar Email' : 'Change Email'}
        </h3>
        <p className="text-sm text-gray-600 mb-4">
          {language === 'es'
            ? 'Para cambiar tu dirección de email, por favor contacta al soporte.'
            : 'To change your email address, please contact support.'}
        </p>
        <Button variant="outline" size="sm" disabled>
          {language === 'es' ? 'Contactar Soporte' : 'Contact Support'}
        </Button>
      </Card>
    </div>
  );
}
