'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from '@/context/AuthContext';
import { apiRequest, uploadFile } from '@/lib/api';
import { getMediaUrl } from '@/lib/media';
import { toast } from '@/context/ToastContext';
import {
  User,
  Mail,
  Phone,
  Lock,
  Pencil,
  Camera,
  Check,
  X,
  Loader2,
  AlertTriangle,
  GraduationCap,
  Eye,
  EyeOff,
} from 'lucide-react';

export default function StudentProfilePage() {
  const { user, login } = useAuth();
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Profile Information State
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [avatarUrl, setAvatarUrl] = useState('');

  // Password Reset State
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);

  // Editing Mode Toggles
  const [isEditingInfo, setIsEditingInfo] = useState(false);
  const [isEditingPassword, setIsEditingPassword] = useState(false);

  // Status & Feedback States
  const [infoError, setInfoError] = useState('');
  const [passError, setPassError] = useState('');
  const [savingInfo, setSavingInfo] = useState(false);
  const [savingPassword, setSavingPassword] = useState(false);
  const [uploadingAvatar, setUploadingAvatar] = useState(false);

  useEffect(() => {
    if (user) {
      setName(user.name || '');
      setEmail(user.email || '');
      setPhoneNumber(user.phoneNumber || '');
      setAvatarUrl((user as any).avatarUrl || '');
    }
  }, [user]);

  // Avatar Select Handler
  const handleAvatarSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!user?.id) {
      toast.error('Student session not found. Please log in again.');
      return;
    }

    setUploadingAvatar(true);
    const uploadRes = await uploadFile(file, 'general');
    setUploadingAvatar(false);

    if (uploadRes.success && (uploadRes.url || uploadRes.relativeUrl)) {
      const newAvatarUrl = uploadRes.url || uploadRes.relativeUrl;
      setAvatarUrl(newAvatarUrl);

      // Save to backend student profile
      const saveRes = await apiRequest(`/students/${user.id}`, {
        method: 'PUT',
        body: JSON.stringify({ avatarUrl: newAvatarUrl }),
      });

      if (saveRes.success) {
        toast.success('Profile picture updated!');
        const token = localStorage.getItem('ags_token');
        if (token) {
          login(token, {
            ...user,
            avatarUrl: newAvatarUrl,
          });
        }
      } else {
        toast.error(saveRes.error || 'Failed to save profile picture');
      }
    } else {
      toast.error(uploadRes.error || 'Failed to upload image');
    }
  };

  // Update Personal Information (Name, Email, Phone)
  const handleUpdateProfileInfo = async (e: React.FormEvent) => {
    e.preventDefault();
    setInfoError('');

    if (!name.trim() || !email.trim()) {
      setInfoError('Name and email cannot be empty');
      toast.error('Name and email cannot be empty');
      return;
    }

    if (!user?.id) {
      setInfoError('Student user ID not found. Please log in again.');
      return;
    }

    setSavingInfo(true);
    const res = await apiRequest(`/students/${user.id}`, {
      method: 'PUT',
      body: JSON.stringify({
        name,
        email,
        phoneNumber,
      }),
    });
    setSavingInfo(false);

    if (res.success && res.student) {
      toast.success('Personal information updated successfully!');
      setIsEditingInfo(false);

      const token = localStorage.getItem('ags_token');
      if (token) {
        login(token, {
          id: res.student.id || res.student._id,
          name: res.student.name,
          email: res.student.email,
          phoneNumber: res.student.phoneNumber,
          role: 'student',
        });
      }
    } else {
      setInfoError(res.error || 'Failed to update profile information.');
      toast.error(res.error || 'Failed to update profile information.');
    }
  };

  // Change Password
  const handleResetPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setPassError('');

    if (!newPassword || newPassword.length < 6) {
      setPassError('New password must be at least 6 characters long.');
      toast.warning('New password must be at least 6 characters long.');
      return;
    }

    if (newPassword !== confirmPassword) {
      setPassError('New password and confirm password do not match.');
      toast.warning('New password and confirm password do not match.');
      return;
    }

    if (!user?.id) {
      setPassError('Student user ID not found. Please log in again.');
      return;
    }

    setSavingPassword(true);
    const res = await apiRequest(`/students/${user.id}`, {
      method: 'PUT',
      body: JSON.stringify({
        password: newPassword,
      }),
    });
    setSavingPassword(false);

    if (res.success) {
      toast.success('Your password has been changed successfully!');
      setIsEditingPassword(false);
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } else {
      setPassError(res.error || 'Failed to update password.');
      toast.error(res.error || 'Failed to update password.');
    }
  };

  return (
    <div className="space-y-8 max-w-6xl mx-auto">
      {/* Top Header */}
      <div>
        <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight">My Profile</h1>
        <p className="text-sm text-gray-500 mt-1">
          Manage your personal account details, contact information, and security
        </p>
      </div>

      {/* Hidden File Input for Avatar Upload */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleAvatarSelect}
        className="hidden"
      />

      {/* Profile Avatar Card */}
      <div className="bg-white rounded-3xl p-6 sm:p-8 border border-gray-200 shadow-xs flex flex-col sm:flex-row items-center gap-6">
        <div className="relative shrink-0">
          <div className="w-24 h-24 rounded-full bg-[#FECE00] text-black font-black flex items-center justify-center text-4xl shadow-md border-4 border-amber-200/50 overflow-hidden">
            {avatarUrl ? (
              <img src={getMediaUrl(avatarUrl, 'images')} alt={name} className="w-full h-full object-cover" />
            ) : (
              name.charAt(0) || 'S'
            )}
          </div>
          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            disabled={uploadingAvatar}
            className="absolute bottom-0 right-0 w-8 h-8 rounded-full bg-slate-900 text-white border-2 border-white flex items-center justify-center hover:bg-slate-800 transition shadow-sm cursor-pointer"
            title="Upload Profile Picture"
          >
            {uploadingAvatar ? (
              <Loader2 className="w-4 h-4 text-[#FECE00] animate-spin" />
            ) : (
              <Camera className="w-4 h-4 text-[#FECE00]" />
            )}
          </button>
        </div>

        <div className="text-center sm:text-left space-y-1">
          <h2 className="text-xl font-bold text-gray-900">{name || 'Student User'}</h2>
          <p className="text-xs font-semibold text-gray-500 flex items-center justify-center sm:justify-start gap-1.5">
            <GraduationCap className="w-4 h-4 text-amber-600" />
            Enrolled Student Account
          </p>
        </div>
      </div>

      {/* Personal Information Card */}
      <div className="bg-white rounded-3xl p-6 sm:p-8 border border-gray-200 shadow-xs space-y-6">
        <div className="flex items-center justify-between border-b border-gray-100 pb-4">
          <h3 className="text-lg font-bold text-gray-900">Personal Details</h3>
          {!isEditingInfo ? (
            <button
              onClick={() => setIsEditingInfo(true)}
              className="px-4 py-2 bg-[#FECE00] hover:bg-[#e5b800] text-black text-sm font-medium rounded-lg shadow-sm transition-colors flex items-center gap-1.5 cursor-pointer"
            >
              <Pencil className="w-3.5 h-3.5 text-black" />
              <span>Edit Details</span>
            </button>
          ) : (
            <div className="flex items-center gap-2">
              <button
                onClick={() => {
                  setIsEditingInfo(false);
                  if (user) {
                    setName(user.name || '');
                    setEmail(user.email || '');
                    setPhoneNumber(user.phoneNumber || '');
                  }
                }}
                className="px-4 py-2 bg-white text-gray-700 text-sm font-medium border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-200 transition-colors flex items-center gap-1.5 cursor-pointer"
              >
                <X className="w-3.5 h-3.5" />
                <span>Cancel</span>
              </button>
              <button
                form="student-info-form"
                type="submit"
                disabled={savingInfo}
                className="px-4 py-2 bg-[#FECE00] hover:bg-[#e5b800] text-black text-sm font-medium rounded-lg shadow-sm transition-colors flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
              >
                <Check className="w-3.5 h-3.5 text-black" />
                <span>{savingInfo ? 'Saving...' : 'Save Changes'}</span>
              </button>
            </div>
          )}
        </div>

        {infoError && (
          <div className="p-3.5 rounded-2xl bg-red-50 border border-red-200 text-red-700 text-xs font-semibold flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-red-600 shrink-0" />
            <span>{infoError}</span>
          </div>
        )}

        {isEditingInfo ? (
          <form id="student-info-form" onSubmit={handleUpdateProfileInfo} className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div>
              <label className="block text-xs font-semibold text-gray-500 mb-1.5">Full Name *</label>
              <div className="relative">
                <User className="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-500 mb-1.5">Email Address *</label>
              <div className="relative">
                <Mail className="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-500 mb-1.5">Phone Number</label>
              <div className="relative">
                <Phone className="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                <input
                  type="tel"
                  value={phoneNumber}
                  onChange={(e) => setPhoneNumber(e.target.value)}
                  placeholder="+49 123 4567890"
                  className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none"
                />
              </div>
            </div>
          </form>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-y-6 gap-x-8">
            <div>
              <p className="text-xs font-semibold text-gray-400 mb-1">Full Name</p>
              <p className="text-base font-bold text-gray-900">{name || 'N/A'}</p>
            </div>

            <div>
              <p className="text-xs font-semibold text-gray-400 mb-1">Email Address</p>
              <p className="text-base font-bold text-gray-900 break-all">{email || 'N/A'}</p>
            </div>

            <div>
              <p className="text-xs font-semibold text-gray-400 mb-1">Phone Number</p>
              <p className="text-base font-bold text-gray-900">{phoneNumber || 'Not provided'}</p>
            </div>
          </div>
        )}
      </div>

      {/* Security & Password Card */}
      <div className="bg-white rounded-3xl p-6 sm:p-8 border border-gray-200 shadow-xs space-y-6">
        <div className="flex items-center justify-between border-b border-gray-100 pb-4">
          <h3 className="text-lg font-bold text-gray-900">Security & Password</h3>
          {!isEditingPassword ? (
            <button
              onClick={() => setIsEditingPassword(true)}
              className="px-4 py-2 bg-[#FECE00] hover:bg-[#e5b800] text-black text-sm font-medium rounded-lg shadow-sm transition-colors flex items-center gap-1.5 cursor-pointer"
            >
              <Pencil className="w-3.5 h-3.5 text-black" />
              <span>Change Password</span>
            </button>
          ) : (
            <div className="flex items-center gap-2">
              <button
                onClick={() => {
                  setIsEditingPassword(false);
                  setNewPassword('');
                  setConfirmPassword('');
                }}
                className="px-4 py-2 bg-white text-gray-700 text-sm font-medium border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-200 transition-colors flex items-center gap-1.5 cursor-pointer"
              >
                <X className="w-3.5 h-3.5" />
                <span>Cancel</span>
              </button>
              <button
                form="student-password-form"
                type="submit"
                disabled={savingPassword}
                className="px-4 py-2 bg-[#FECE00] hover:bg-[#e5b800] text-black text-sm font-medium rounded-lg shadow-sm transition-colors flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
              >
                <Check className="w-3.5 h-3.5 text-black" />
                <span>{savingPassword ? 'Updating...' : 'Save Password'}</span>
              </button>
            </div>
          )}
        </div>

        {passError && (
          <div className="p-3.5 rounded-2xl bg-red-50 border border-red-200 text-red-700 text-xs font-semibold flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-red-600 shrink-0" />
            <span>{passError}</span>
          </div>
        )}

        {isEditingPassword ? (
          <form id="student-password-form" onSubmit={handleResetPassword} className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-xs font-semibold text-gray-500 mb-1.5">New Password *</label>
              <div className="relative">
                <Lock className="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                <input
                  type={showPassword ? 'text' : 'password'}
                  required
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  placeholder="At least 6 characters"
                  className="w-full pl-9 pr-9 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3.5 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-700 transition focus:outline-none"
                  title={showPassword ? 'Hide password' : 'Show password'}
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-500 mb-1.5">Confirm New Password *</label>
              <div className="relative">
                <Lock className="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                <input
                  type={showPassword ? 'text' : 'password'}
                  required
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder="Re-enter new password"
                  className="w-full pl-9 pr-9 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3.5 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-700 transition focus:outline-none"
                  title={showPassword ? 'Hide password' : 'Show password'}
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>
          </form>
        ) : (
          <div>
            <p className="text-xs font-semibold text-gray-400 mb-1">Password Security</p>
            <p className="text-base font-bold text-gray-900 tracking-widest font-mono">••••••••••••</p>
          </div>
        )}
      </div>
    </div>
  );
}
