import React, { useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { 
  User, 
  Mail, 
  Phone, 
  MapPin, 
  Calendar, 
  Settings, 
  Shield,
  CreditCard,
  Bell,
  Lock,
  Globe
} from 'lucide-react';
import { toast } from 'sonner';

const Profile = () => {
  const { user } = useAuth();
  const [isEditing, setIsEditing] = useState(false);
  const [formData, setFormData] = useState({
    name: user?.name || '',
    email: user?.email || '',
    phone: (user as any)?.profile?.phone || '',
    address: (user as any)?.profile?.address || '',
    language: user?.preferences?.language || 'es'
  });

  const handleSave = () => {
    // Simulate saving to localStorage
    const updatedUser = {
      ...user,
      name: formData.name,
      email: formData.email,
      profile: {
        ...(user as any)?.profile,
        phone: formData.phone,
        address: formData.address
      },
      preferences: {
        ...user?.preferences,
        language: formData.language
      }
    };
    
    localStorage.setItem('karibeo-user', JSON.stringify(updatedUser));
    toast.success('Perfil actualizado correctamente');
    setIsEditing(false);
  };

  const getRoleDisplay = (role: string) => {
    const roleMap = {
      'super_admin': 'Super Administrador',
      'admin': 'Administrador', 
      'tourist': 'Turista',
      'guide': 'Guía Turístico',
      'hotel': 'Hotel',
      'taxi': 'Taxista',
      'restaurant': 'Restaurante'
    };
    return roleMap[role as keyof typeof roleMap] || role;
  };

  const getRoleBadgeColor = (role: string) => {
    const colorMap = {
      'super_admin': 'bg-gradient-to-r from-purple-500 to-pink-500',
      'admin': 'bg-gradient-to-r from-blue-500 to-cyan-500',
      'tourist': 'bg-gradient-to-r from-green-500 to-emerald-500',
      'guide': 'bg-gradient-to-r from-yellow-500 to-orange-500',
      'hotel': 'bg-gradient-to-r from-indigo-500 to-purple-500',
      'taxi': 'bg-gradient-to-r from-red-500 to-pink-500',
      'restaurant': 'bg-gradient-to-r from-orange-500 to-red-500'
    };
    return colorMap[role as keyof typeof colorMap] || 'bg-gray-500';
  };

  return (
    <div className="mobile-safe-top p-4 lg:p-6 space-y-4 lg:space-y-6">
      {/* Mobile Header */}
      <div className="mobile-header lg:hidden">
        <h1 className="mobile-title">Profile</h1>
        <p className="text-muted-foreground text-sm">Manage your account information</p>
      </div>

      {/* Profile Header */}
      <div className="mobile-card">
        <div className="p-4 lg:p-6">
          <div className="flex flex-col lg:flex-row lg:items-center space-y-4 lg:space-y-0 lg:space-x-4">
            <Avatar className="w-16 h-16 lg:w-20 lg:h-20 mx-auto lg:mx-0">
              <AvatarImage src={user?.avatar} />
              <AvatarFallback className="text-base lg:text-lg">
                {user?.name?.split(' ').map(n => n[0]).join('').toUpperCase()}
              </AvatarFallback>
            </Avatar>
            <div className="flex-1 text-center lg:text-left">
              <h2 className="text-xl lg:text-2xl font-bold text-foreground">{user?.name}</h2>
              <p className="text-muted-foreground text-sm lg:text-base">{user?.email}</p>
              <div className="mt-2 flex flex-col sm:flex-row items-center justify-center lg:justify-start space-y-2 sm:space-y-0 sm:space-x-2">
                <Badge className={`text-white text-xs lg:text-sm ${getRoleBadgeColor(user?.role || '')}`}>
                  <Shield className="w-3 h-3 mr-1" />
                  {getRoleDisplay(user?.role || '')}
                </Badge>
                <Badge variant="secondary" className="text-xs lg:text-sm">
                  <Calendar className="w-3 h-3 mr-1" />
                  Miembro desde {(user as any)?.profile?.joinedDate || '2023'}
                </Badge>
              </div>
            </div>
            <Button 
              onClick={() => setIsEditing(!isEditing)}
              variant={isEditing ? "secondary" : "default"}
              className="mobile-btn w-full lg:w-auto"
            >
              {isEditing ? 'Cancelar' : 'Editar Perfil'}
            </Button>
          </div>
        </div>
      </div>

      <Tabs defaultValue="personal" className="space-y-4">
        <TabsList className="grid w-full grid-cols-2 lg:grid-cols-4 h-auto">
          <TabsTrigger value="personal" className="text-xs lg:text-sm px-2 lg:px-4 py-2">
            <span className="hidden sm:inline">Información </span>Personal
          </TabsTrigger>
          <TabsTrigger value="security" className="text-xs lg:text-sm px-2 lg:px-4 py-2">Seguridad</TabsTrigger>
          <TabsTrigger value="preferences" className="text-xs lg:text-sm px-2 lg:px-4 py-2">Preferencias</TabsTrigger>
          <TabsTrigger value="billing" className="text-xs lg:text-sm px-2 lg:px-4 py-2">Facturación</TabsTrigger>
        </TabsList>

        <TabsContent value="personal" className="space-y-4">
          <div className="mobile-card">
            <div className="p-4 lg:p-6">
              <div className="flex items-center space-x-2 mb-4 lg:mb-6">
                <User className="w-4 h-4 lg:w-5 lg:h-5" />
                <span className="text-lg lg:text-xl font-semibold">Datos Personales</span>
              </div>
              <div className="space-y-4">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="name" className="text-sm font-medium">Nombre Completo</Label>
                    <Input
                      id="name"
                      value={formData.name}
                      onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                      disabled={!isEditing}
                      className="mobile-input"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="email" className="text-sm font-medium">Correo Electrónico</Label>
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                      disabled={!isEditing}
                      className="mobile-input"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="phone" className="text-sm font-medium">Teléfono</Label>
                    <Input
                      id="phone"
                      value={formData.phone}
                      onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                      disabled={!isEditing}
                      className="mobile-input"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="address" className="text-sm font-medium">Dirección</Label>
                    <Input
                      id="address"
                      value={formData.address}
                      onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                      disabled={!isEditing}
                      className="mobile-input"
                    />
                  </div>
                </div>
                {isEditing && (
                  <div className="flex flex-col sm:flex-row justify-end space-y-2 sm:space-y-0 sm:space-x-2 pt-4">
                    <Button variant="outline" onClick={() => setIsEditing(false)} className="mobile-btn">
                      Cancelar
                    </Button>
                    <Button onClick={handleSave} className="mobile-btn">
                      Guardar Cambios
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="security" className="space-y-4">
          <div className="mobile-card">
            <div className="p-4 lg:p-6">
              <div className="flex items-center space-x-2 mb-4 lg:mb-6">
                <Lock className="w-4 h-4 lg:w-5 lg:h-5" />
                <span className="text-lg lg:text-xl font-semibold">Configuración de Seguridad</span>
              </div>
              <div className="space-y-4">
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex-1">
                    <h4 className="font-medium text-sm lg:text-base">Cambiar Contraseña</h4>
                    <p className="text-xs lg:text-sm text-muted-foreground">Actualiza tu contraseña periódicamente</p>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Cambiar</Button>
                </div>
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex-1">
                    <h4 className="font-medium text-sm lg:text-base">Autenticación de Dos Factores</h4>
                    <p className="text-xs lg:text-sm text-muted-foreground">Agrega una capa extra de seguridad</p>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Configurar</Button>
                </div>
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex-1">
                    <h4 className="font-medium text-sm lg:text-base">Sesiones Activas</h4>
                    <p className="text-xs lg:text-sm text-muted-foreground">Gestiona tus sesiones en otros dispositivos</p>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Ver Sesiones</Button>
                </div>
              </div>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="preferences" className="space-y-4">
          <div className="mobile-card">
            <div className="p-4 lg:p-6">
              <div className="flex items-center space-x-2 mb-4 lg:mb-6">
                <Settings className="w-4 h-4 lg:w-5 lg:h-5" />
                <span className="text-lg lg:text-xl font-semibold">Preferencias</span>
              </div>
              <div className="space-y-4">
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex items-center space-x-3">
                    <Globe className="w-4 h-4 lg:w-5 lg:h-5 text-muted-foreground flex-shrink-0" />
                    <div className="min-w-0 flex-1">
                      <h4 className="font-medium text-sm lg:text-base">Idioma</h4>
                      <p className="text-xs lg:text-sm text-muted-foreground">Español</p>
                    </div>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Cambiar</Button>
                </div>
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex items-center space-x-3">
                    <Bell className="w-4 h-4 lg:w-5 lg:h-5 text-muted-foreground flex-shrink-0" />
                    <div className="min-w-0 flex-1">
                      <h4 className="font-medium text-sm lg:text-base">Notificaciones</h4>
                      <p className="text-xs lg:text-sm text-muted-foreground">Email y push activadas</p>
                    </div>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Configurar</Button>
                </div>
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex items-center space-x-3">
                    <MapPin className="w-4 h-4 lg:w-5 lg:h-5 text-muted-foreground flex-shrink-0" />
                    <div className="min-w-0 flex-1">
                      <h4 className="font-medium text-sm lg:text-base">Ubicación</h4>
                      <p className="text-xs lg:text-sm text-muted-foreground">Compartir ubicación para mejores recomendaciones</p>
                    </div>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Gestionar</Button>
                </div>
              </div>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="billing" className="space-y-4">
          <div className="mobile-card">
            <div className="p-4 lg:p-6">
              <div className="flex items-center space-x-2 mb-4 lg:mb-6">
                <CreditCard className="w-4 h-4 lg:w-5 lg:h-5" />
                <span className="text-lg lg:text-xl font-semibold">Información de Facturación</span>
              </div>
              <div className="space-y-4">
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex-1">
                    <h4 className="font-medium text-sm lg:text-base">Métodos de Pago</h4>
                    <p className="text-xs lg:text-sm text-muted-foreground">Gestiona tus tarjetas y métodos de pago</p>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Gestionar</Button>
                </div>
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex-1">
                    <h4 className="font-medium text-sm lg:text-base">Historial de Facturas</h4>
                    <p className="text-xs lg:text-sm text-muted-foreground">Ver todas tus facturas y recibos</p>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Ver Historial</Button>
                </div>
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between p-3 lg:p-4 border rounded-lg space-y-3 lg:space-y-0">
                  <div className="flex-1">
                    <h4 className="font-medium text-sm lg:text-base">Suscripción</h4>
                    <p className="text-xs lg:text-sm text-muted-foreground">Plan actual y renovación</p>
                  </div>
                  <Button variant="outline" className="mobile-btn lg:w-auto">Ver Plan</Button>
                </div>
              </div>
            </div>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
};

export default Profile;