'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/lib/auth-store';
import { useTheme } from '@/components/ThemeProvider';
import { 
  User, Settings, Ticket, Calendar, MapPin, 
  Download, Trash2, Lock, Bell, CreditCard, 
  MapPinned, Palette, CheckCircle,
  Eye, Edit, LogOut, X
} from 'lucide-react';
import { apiClient } from '@/lib/api-client';
import { useQuery, useMutation } from '@tanstack/react-query';
import CustomModal from '@/components/CustomModal';

type Tab = 'bookings' | 'profile' | 'settings';

interface Booking {
  id: string;
  pnr: string;
  status: string;
  totalMinor: number;
  createdAt: string;
  trip?: {
    trainNumber: string;
    departureAt: string;
    origin?: { name: string };
    destination?: { name: string };
  };
}

export default function ProfilePage() {
  const router = useRouter();
  const { user, isAuthenticated, logout, initialize, updateUser, isInitialized, fetchProfile } = useAuthStore();
  const { theme, setTheme } = useTheme();
  const [activeTab, setActiveTab] = useState<Tab>('bookings');
  const [showModal, setShowModal] = useState(false);
  const [modalConfig, setModalConfig] = useState<any>({});
  const [showEditProfile, setShowEditProfile] = useState(false);
  const [showChangePassword, setShowChangePassword] = useState(false);
  const [editForm, setEditForm] = useState({
    fullName: '',
    phone: '',
    email: '',
    dateOfBirth: '',
    gender: '',
    nationality: '',
  });
  const [settings, setSettings] = useState({
    notifications: true,
    emailNotifications: true,
    smsNotifications: false,
    preferredOrigin: '',
    preferredPaymentMethod: 'TELEBIRR',
    preferredCurrency: 'ETB',
    preferredLanguage: 'en',
  });

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

  useEffect(() => {
    if (!isInitialized) return;
    
    if (isAuthenticated && user) {
      fetchProfile().catch(() => {
        router.push('/login?redirect=/profile');
      });
      
      setEditForm({
        fullName: user.fullName || '',
        phone: user.phone || '',
        email: user.email || '',
        dateOfBirth: user.dateOfBirth || '',
        gender: user.gender || '',
        nationality: user.nationality || '',
      });
    } else if (!isAuthenticated) {
      router.push('/login?redirect=/profile');
    }
  }, [isInitialized, isAuthenticated, user, router, fetchProfile]);

  const { data: bookings, isLoading: loadingBookings } = useQuery({
    queryKey: ['user-bookings'],
    queryFn: async () => {
      try {
        return await apiClient.get('/bookings/my-bookings');
      } catch {
        return [];
      }
    },
    enabled: isAuthenticated && activeTab === 'bookings',
  });

  const updateProfileMutation = useMutation({
    mutationFn: (data: any) => apiClient.patch('/auth/profile', data),
    onSuccess: (response) => {
      const updatedData = (response as any).data || response;
      updateUser(updatedData);
      setShowEditProfile(false);
      setModalConfig({
        type: 'success',
        title: 'Profile Updated',
        message: 'Your profile has been updated successfully.',
      });
      setShowModal(true);
    },
    onError: (error: any) => {
      setModalConfig({
        type: 'error',
        title: 'Error',
        message: error.response?.data?.message || 'Failed to update profile. Please try again.',
      });
      setShowModal(true);
    },
  });

  const changePasswordMutation = useMutation({
    mutationFn: (data: { currentPassword: string; newPassword: string }) =>
      apiClient.patch('/auth/change-password', data),
    onSuccess: () => {
      setShowChangePassword(false);
      setModalConfig({
        type: 'success',
        title: 'Password Changed',
        message: 'Your password has been updated successfully.',
      });
      setShowModal(true);
    },
    onError: (error: any) => {
      setModalConfig({
        type: 'error',
        title: 'Error',
        message: error.response?.data?.message || 'Failed to change password. Please check your current password.',
      });
      setShowModal(true);
    },
  });

  const downloadDataMutation = useMutation({
    mutationFn: () => apiClient.get('/auth/download-data'),
    onSuccess: (data) => {
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `edr-data-${new Date().toISOString()}.json`;
      a.click();
      setModalConfig({
        type: 'success',
        title: 'Data Downloaded',
        message: 'Your data has been downloaded successfully.',
      });
      setShowModal(true);
    },
  });

  const deleteAccountMutation = useMutation({
    mutationFn: () => apiClient.delete('/auth/account'),
    onSuccess: () => {
      logout();
      router.push('/booking/search');
    },
  });

  const handleEditProfile = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    updateProfileMutation.mutate(editForm);
  };

  const handleChangePassword = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const currentPassword = formData.get('currentPassword') as string;
    const newPassword = formData.get('newPassword') as string;
    const confirmPassword = formData.get('confirmPassword') as string;

    if (newPassword !== confirmPassword) {
      setModalConfig({
        type: 'error',
        title: 'Password Mismatch',
        message: 'New passwords do not match.',
      });
      setShowModal(true);
      return;
    }

    changePasswordMutation.mutate({ currentPassword, newPassword });
    e.currentTarget.reset();
  };

  const handleLogout = () => {
    setModalConfig({
      type: 'warning',
      title: 'Sign Out',
      message: 'Are you sure you want to sign out?',
      onConfirm: async () => {
        await logout();
      },
    });
    setShowModal(true);
  };

  const handleDownloadData = () => {
    setModalConfig({
      type: 'warning',
      title: 'Download Your Data',
      message: 'This will download all your personal data in JSON format. Continue?',
      onConfirm: () => {
        downloadDataMutation.mutate();
        setShowModal(false);
      },
    });
    setShowModal(true);
  };

  const handleDeleteAccount = () => {
    setModalConfig({
      type: 'error',
      title: 'Delete Account',
      message: 'This action cannot be undone. All your data will be permanently deleted. Are you sure?',
      onConfirm: () => {
        deleteAccountMutation.mutate();
        setShowModal(false);
      },
    });
    setShowModal(true);
  };

  const getStatusBadge = (status: string) => {
    const styles = {
      CONFIRMED: 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300',
      PENDING: 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300',
      CANCELLED: 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300',
      COMPLETED: 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300',
    };
    return styles[status as keyof typeof styles] || styles.PENDING;
  };

  if (!isInitialized || !user) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[rgb(20_113_76)]"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
      <div className="container mx-auto px-4">
        <div className="max-w-6xl mx-auto">
          {/* Header */}
          <div className="card mb-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="w-16 h-16 bg-[rgb(20_113_76)] rounded-full flex items-center justify-center">
                  <User className="w-8 h-8 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">{user.fullName}</h1>
                  <p className="text-gray-600 dark:text-gray-400">{user.email}</p>
                  {user.faydaVerified && (
                    <span className="inline-flex items-center gap-1 text-xs text-green-600 dark:text-green-400 mt-1">
                      <CheckCircle className="w-3 h-3" />
                      Verified with Fayda
                    </span>
                  )}
                </div>
              </div>
              <button
                onClick={handleLogout}
                className="btn-secondary flex items-center gap-2"
              >
                <LogOut className="w-4 h-4" />
                Sign Out
              </button>
            </div>
          </div>

          {/* Tabs */}
          <div className="card mb-6">
            <div className="flex gap-2 border-b dark:border-gray-700 pb-2">
              <button
                onClick={() => setActiveTab('bookings')}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                  activeTab === 'bookings'
                    ? 'bg-[rgb(20_113_76)] text-white'
                    : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'
                }`}
              >
                <Ticket className="w-4 h-4" />
                Bookings
              </button>
              <button
                onClick={() => setActiveTab('profile')}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                  activeTab === 'profile'
                    ? 'bg-[rgb(20_113_76)] text-white'
                    : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'
                }`}
              >
                <User className="w-4 h-4" />
                Profile
              </button>
              <button
                onClick={() => setActiveTab('settings')}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                  activeTab === 'settings'
                    ? 'bg-[rgb(20_113_76)] text-white'
                    : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'
                }`}
              >
                <Settings className="w-4 h-4" />
                Settings
              </button>
            </div>
          </div>

          {/* Tab Content */}
          {activeTab === 'bookings' && (
            <div className="space-y-4">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">Bookings</h2>
              
              {loadingBookings ? (
                <div className="card text-center py-12">
                  <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[rgb(20_113_76)] mx-auto"></div>
                  <p className="text-gray-600 dark:text-gray-400 mt-4">Loading bookings...</p>
                </div>
              ) : bookings && Array.isArray(bookings) && bookings.length > 0 ? (
                bookings.map((booking: Booking) => (
                  <div key={booking.id} className="card hover:shadow-lg transition-shadow">
                    <div className="flex items-center justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-3">
                          <span className={`badge ${getStatusBadge(booking.status)}`}>
                            {booking.status}
                          </span>
                          <span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
                            PNR: {booking.pnr}
                          </span>
                        </div>
                        
                        <div className="grid md:grid-cols-3 gap-4 text-sm">
                          <div className="flex items-center gap-2">
                            <Calendar className="w-4 h-4 text-gray-400" />
                            <span className="text-gray-600 dark:text-gray-400">
                              {booking.trip?.departureAt 
                                ? new Date(booking.trip.departureAt).toLocaleDateString() 
                                : 'N/A'}
                            </span>
                          </div>
                          <div className="flex items-center gap-2">
                            <MapPin className="w-4 h-4 text-gray-400" />
                            <span className="text-gray-600 dark:text-gray-400">
                              {booking.trip?.origin?.name} → {booking.trip?.destination?.name}
                            </span>
                          </div>
                          <div className="flex items-center gap-2">
                            <CreditCard className="w-4 h-4 text-gray-400" />
                            <span className="text-gray-900 dark:text-gray-100 font-semibold">
                              ETB {((booking.totalMinor || 0) / 100).toFixed(2)}
                            </span>
                          </div>
                        </div>
                      </div>
                      
                      <div className="flex items-center gap-2 ml-4">
                        <button
                          onClick={() => router.push(`/booking/confirmation?id=${booking.id}`)}
                          className="btn-secondary text-sm flex items-center gap-2"
                        >
                          <Eye className="w-4 h-4" />
                          View
                        </button>
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="card text-center py-12">
                  <Ticket className="w-16 h-16 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
                  <p className="text-gray-600 dark:text-gray-400 mb-4">No bookings yet</p>
                  <button onClick={() => router.push('/booking/search')} className="btn-primary">
                    Book Your First Trip
                  </button>
                </div>
              )}
            </div>
          )}

          {activeTab === 'profile' && (
            <div className="space-y-6">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">Profile Information</h2>
              
              <div className="card">
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Full Name</label>
                    <div className="input-field bg-gray-50 dark:bg-gray-800">{user.fullName}</div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Date of Birth</label>
                    <div className="input-field bg-gray-50 dark:bg-gray-800">
                      {user.dateOfBirth ? new Date(user.dateOfBirth).toLocaleDateString() : 'Not set'}
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Gender</label>
                    <div className="input-field bg-gray-50 dark:bg-gray-800">{user.gender || 'Not set'}</div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Nationality</label>
                    <div className="input-field bg-gray-50 dark:bg-gray-800">{user.nationality || 'Not set'}</div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Email</label>
                    <div className="input-field bg-gray-50 dark:bg-gray-800">{user.email}</div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Phone</label>
                    <div className="input-field bg-gray-50 dark:bg-gray-800">{user.phone || 'Not set'}</div>
                  </div>
                </div>
                
                <div className="mt-6 flex justify-end">
                  <button 
                    onClick={() => setShowEditProfile(true)}
                    className="btn-secondary flex items-center gap-2"
                  >
                    <Edit className="w-4 h-4" />
                    Edit Profile
                  </button>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'settings' && (
            <div className="space-y-6">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">Settings</h2>
              
              {/* Appearance */}
              <div className="card">
                <h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-900 dark:text-gray-100">
                  <Palette className="w-5 h-5" />
                  Appearance
                </h3>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Theme</label>
                    <select
                      value={theme}
                      onChange={(e) => setTheme(e.target.value as any)}
                      className="input-field"
                    >
                      <option value="light">Light</option>
                      <option value="dark">Dark</option>
                      <option value="system">System</option>
                    </select>
                  </div>
                </div>
              </div>

              {/* Notifications */}
              <div className="card">
                <h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-900 dark:text-gray-100">
                  <Bell className="w-5 h-5" />
                  Notifications
                </h3>
                <div className="space-y-4">
                  <label className="flex items-center justify-between cursor-pointer group">
                    <span className="text-sm text-gray-700 dark:text-gray-300">Push Notifications</span>
                    <div className="relative inline-block w-12 h-6">
                      <input
                        type="checkbox"
                        checked={settings.notifications}
                        onChange={(e) => setSettings({ ...settings, notifications: e.target.checked })}
                        className="sr-only peer"
                      />
                      <div className="w-12 h-6 bg-gray-300 dark:bg-gray-600 rounded-full peer peer-checked:bg-[rgb(20_113_76)] transition-colors"></div>
                      <div className="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform peer-checked:translate-x-6"></div>
                    </div>
                  </label>
                  <label className="flex items-center justify-between cursor-pointer group">
                    <span className="text-sm text-gray-700 dark:text-gray-300">Email Notifications</span>
                    <div className="relative inline-block w-12 h-6">
                      <input
                        type="checkbox"
                        checked={settings.emailNotifications}
                        onChange={(e) => setSettings({ ...settings, emailNotifications: e.target.checked })}
                        className="sr-only peer"
                      />
                      <div className="w-12 h-6 bg-gray-300 dark:bg-gray-600 rounded-full peer peer-checked:bg-[rgb(20_113_76)] transition-colors"></div>
                      <div className="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform peer-checked:translate-x-6"></div>
                    </div>
                  </label>
                  <label className="flex items-center justify-between cursor-pointer group">
                    <span className="text-sm text-gray-700 dark:text-gray-300">SMS Notifications</span>
                    <div className="relative inline-block w-12 h-6">
                      <input
                        type="checkbox"
                        checked={settings.smsNotifications}
                        onChange={(e) => setSettings({ ...settings, smsNotifications: e.target.checked })}
                        className="sr-only peer"
                      />
                      <div className="w-12 h-6 bg-gray-300 dark:bg-gray-600 rounded-full peer peer-checked:bg-[rgb(20_113_76)] transition-colors"></div>
                      <div className="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform peer-checked:translate-x-6"></div>
                    </div>
                  </label>
                </div>
              </div>

              {/* Preferences */}
              <div className="card">
                <h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-900 dark:text-gray-100">
                  <MapPinned className="w-5 h-5" />
                  Preferences
                </h3>
                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Preferred Origin</label>
                    <input
                      type="text"
                      value={settings.preferredOrigin}
                      onChange={(e) => setSettings({ ...settings, preferredOrigin: e.target.value })}
                      className="input-field"
                      placeholder="e.g., Lebu"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Preferred Payment Method</label>
                    <select
                      value={settings.preferredPaymentMethod}
                      onChange={(e) => setSettings({ ...settings, preferredPaymentMethod: e.target.value })}
                      className="input-field"
                    >
                      <option value="TELEBIRR">Telebirr</option>
                      <option value="CBE_BIRR">CBE Birr</option>
                      <option value="CARD">Credit/Debit Card</option>
                      <option value="WALLET">E-Wallet</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Preferred Currency</label>
                    <select
                      value={settings.preferredCurrency}
                      onChange={(e) => setSettings({ ...settings, preferredCurrency: e.target.value })}
                      className="input-field"
                    >
                      <option value="ETB">ETB (Ethiopian Birr)</option>
                      <option value="DJF">DJF (Djiboutian Franc)</option>
                      <option value="USD">USD (US Dollar)</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Language</label>
                    <select
                      value={settings.preferredLanguage}
                      onChange={(e) => setSettings({ ...settings, preferredLanguage: e.target.value })}
                      className="input-field"
                    >
                      <option value="en">English</option>
                      <option value="am">አማርኛ (Amharic)</option>
                      <option value="fr">Français (French)</option>
                    </select>
                  </div>
                </div>
              </div>

              {/* Security */}
              <div className="card">
                <h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-900 dark:text-gray-100">
                  <Lock className="w-5 h-5" />
                  Security
                </h3>
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium text-gray-900 dark:text-gray-100">Password</p>
                    <p className="text-sm text-gray-600 dark:text-gray-400">Change your account password</p>
                  </div>
                  <button
                    onClick={() => setShowChangePassword(true)}
                    className="btn-secondary flex items-center gap-2"
                  >
                    <Lock className="w-4 h-4" />
                    Change Password
                  </button>
                </div>
              </div>

              {/* Data & Privacy */}
              <div className="card">
                <h3 className="text-lg font-semibold mb-4 flex items-center gap-2 text-gray-900 dark:text-gray-100">
                  <Download className="w-5 h-5" />
                  Data & Privacy
                </h3>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-medium text-gray-900 dark:text-gray-100">Download Your Data</p>
                      <p className="text-sm text-gray-600 dark:text-gray-400">Get a copy of all your data</p>
                    </div>
                    <button
                      onClick={handleDownloadData}
                      className="btn-secondary flex items-center gap-2"
                      disabled={downloadDataMutation.isPending}
                    >
                      <Download className="w-4 h-4" />
                      Download
                    </button>
                  </div>
                  
                  <div className="border-t dark:border-gray-700 pt-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium text-red-600 dark:text-red-400">Delete Account</p>
                        <p className="text-sm text-gray-600 dark:text-gray-400">Permanently delete your account and all data</p>
                      </div>
                      <button
                        onClick={handleDeleteAccount}
                        className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-semibold rounded-lg transition-colors flex items-center gap-2"
                      >
                        <Trash2 className="w-4 h-4" />
                        Delete
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Edit Profile Modal */}
      {showEditProfile && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full max-h-[90vh] overflow-y-auto">
            <div className="sticky top-0 bg-white dark:bg-gray-800 border-b dark:border-gray-700 px-6 py-4 flex items-center justify-between">
              <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Edit Profile</h3>
              <button
                onClick={() => setShowEditProfile(false)}
                className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            <form onSubmit={handleEditProfile} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Full Name *</label>
                <input
                  type="text"
                  value={editForm.fullName}
                  onChange={(e) => setEditForm({ ...editForm, fullName: e.target.value })}
                  className="input-field"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Date of Birth</label>
                <input
                  type="date"
                  value={editForm.dateOfBirth}
                  onChange={(e) => setEditForm({ ...editForm, dateOfBirth: e.target.value })}
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Gender</label>
                <select
                  value={editForm.gender}
                  onChange={(e) => setEditForm({ ...editForm, gender: e.target.value })}
                  className="input-field"
                >
                  <option value="">Select gender</option>
                  <option value="Male">Male</option>
                  <option value="Female">Female</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Nationality</label>
                <select
                  value={editForm.nationality}
                  onChange={(e) => setEditForm({ ...editForm, nationality: e.target.value })}
                  className="input-field"
                >
                  <option value="">Select nationality</option>
                  <option value="Ethiopian">Ethiopian</option>
                  <option value="Djiboutian">Djiboutian</option>
                  <option value="Other">Other</option>
                </select>
              </div>              
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Email *</label>
                <input
                  type="email"
                  value={editForm.email}
                  onChange={(e) => setEditForm({ ...editForm, email: e.target.value })}
                  className="input-field"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Phone</label>
                <input
                  type="tel"
                  value={editForm.phone}
                  onChange={(e) => setEditForm({ ...editForm, phone: e.target.value })}
                  className="input-field"
                  placeholder="+251911234567"
                />
              </div>
              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setShowEditProfile(false)}
                  className="btn-secondary flex-1"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="btn-primary flex-1"
                  disabled={updateProfileMutation.isPending}
                >
                  {updateProfileMutation.isPending ? 'Saving...' : 'Save Changes'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Change Password Modal */}
      {showChangePassword && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full">
            <div className="sticky top-0 bg-white dark:bg-gray-800 border-b dark:border-gray-700 px-6 py-4 flex items-center justify-between">
              <h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Change Password</h3>
              <button
                onClick={() => setShowChangePassword(false)}
                className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            <form onSubmit={handleChangePassword} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Current Password</label>
                <input
                  type="password"
                  name="currentPassword"
                  className="input-field"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">New Password</label>
                <input
                  type="password"
                  name="newPassword"
                  className="input-field"
                  required
                  minLength={6}
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2 text-gray-700 dark:text-gray-300">Confirm New Password</label>
                <input
                  type="password"
                  name="confirmPassword"
                  className="input-field"
                  required
                  minLength={6}
                />
              </div>
              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={() => setShowChangePassword(false)}
                  className="btn-secondary flex-1"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="btn-primary flex-1"
                  disabled={changePasswordMutation.isPending}
                >
                  {changePasswordMutation.isPending ? 'Changing...' : 'Change Password'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {showModal && (
        <CustomModal
          isOpen={showModal}
          type={modalConfig.type}
          title={modalConfig.title}
          message={modalConfig.message}
          onClose={() => setShowModal(false)}
          onConfirm={modalConfig.onConfirm}
          showCancel={modalConfig.type === 'warning' || modalConfig.type === 'error'}
          confirmText={modalConfig.type === 'warning' || modalConfig.type === 'error' ? 'Yes' : 'OK'}
          cancelText="Cancel"
        />
      )}
    </div>
  );
}
