import React, { useState, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import type { UserRole } from '../../types';
import { useAuth } from '../../context/AuthContext';
import { API_BASE_URL } from '../../lib/config';

const compressImage = (base64Str: string): Promise<string> => {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = base64Str;
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const MAX_WIDTH = 400;
      const MAX_HEIGHT = 400;
      let width = img.width;
      let height = img.height;
      if (width > height) {
        if (width > MAX_WIDTH) {
          height *= MAX_WIDTH / width;
          width = MAX_WIDTH;
        }
      } else {
        if (height > MAX_HEIGHT) {
          width *= MAX_HEIGHT / height;
          height = MAX_HEIGHT;
        }
      }
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      ctx?.drawImage(img, 0, 0, width, height);
      resolve(canvas.toDataURL('image/jpeg', 0.7));
    };
  });
};

interface ProfileViewProps {
  onLogout?: () => void;
  onSupabaseError?: () => void;
}

const ProfileView: React.FC<ProfileViewProps> = ({ onLogout }) => {
  const { user, login } = useAuth();
  const [loading, setLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [regCount, setRegCount] = useState(0);
  const [isEditing, setIsEditing] = useState(false);
  const [editForm, setEditForm] = useState({ 
    name: '', 
    phone: '', 
    profile_photo: '', 
    year: '', 
    section: '',
    email: '',
    role: '',
    department: '',
    collegeName: '',
    collegeLocation: '',
    class: '',
    regNo: ''
  });
  const [showSuccess, setShowSuccess] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [pastEvents, setPastEvents] = useState<any[]>([]);

  const fetchProfile = async () => {
    if (!user) return;
    try {
      setEditForm({
        name: user.fullName || '',
        phone: user.phone || '',
        profile_photo: (user as any).profile_photo || '',
        year: user.year || '',
        section: user.section || '',
        email: user.email || '',
        role: user.role || '',
        department: user.department || '',
        collegeName: user.collegeName || '',
        collegeLocation: (user as any).collegeLocation || '',
        class: (user as any).class || '',
        regNo: user.regNo || ''
      });

      // Fetch registrations and events to compute counts and completed events
      const [regsRes, eventsRes] = await Promise.all([
        fetch(`${API_BASE_URL}/api/registrations?userId=${user.id}`),
        fetch(`${API_BASE_URL}/api/events`)
      ]);

      if (regsRes.ok && eventsRes.ok) {
        const regs = await regsRes.json();
        const events = await eventsRes.json();
        setRegCount(regs.length);

        // Find completed events for this student
        const completedRegs = regs.filter((r: any) => {
          const ev = events.find((e: any) => String(e.id) === String(r.eventId || r.event_id));
          return ev && (ev.status === 'Completed' || ev.status === 'COMPLETED');
        }).map((r: any) => {
          const ev = events.find((e: any) => String(e.id) === String(r.eventId || r.event_id));
          return {
            events: {
              title: ev.title,
              category: ev.category
            },
            participation_date: r.registeredAt || r.registered_at || new Date().toISOString()
          };
        });
        setPastEvents(completedRegs);
      }
    } catch (err) {
      console.error("Failed to load user profile stats:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProfile();
  }, [user?.id]);

  const handleUpdate = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (!user) return;
    setIsSaving(true);
    setErrorMessage(null);
    try {
      const payload = {
        fullName: editForm.name,
        phone: editForm.phone,
        year: editForm.year,
        section: editForm.section,
        profile_photo: editForm.profile_photo,
        email: editForm.email,
        role: editForm.role,
        department: editForm.department,
        collegeName: editForm.collegeName,
        collegeLocation: editForm.collegeLocation,
        class: editForm.class,
        regNo: editForm.regNo
      };

      const res = await fetch(`${API_BASE_URL}/api/admin/users/${user.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      if (!res.ok) {
        throw new Error("Failed to save profile changes.");
      }

      // Update AuthContext to sync globally
      login({
        ...user,
        fullName: editForm.name,
        phone: editForm.phone,
        year: editForm.year,
        section: editForm.section,
        email: editForm.email,
        role: editForm.role as any,
        department: editForm.department,
        collegeName: editForm.collegeName,
        collegeLocation: editForm.collegeLocation,
        class: editForm.class,
        regNo: editForm.regNo,
        profile_photo: editForm.profile_photo
      });

      setIsEditing(false);
      setShowSuccess(true);
      setTimeout(() => setShowSuccess(false), 3000);
    } catch (err: any) {
      setErrorMessage(err.message || "Failed to update profile.");
    } finally {
      setIsSaving(false);
    }
  };

  const handlePhotoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = async () => {
        const compressed = await compressImage(reader.result as string);
        setEditForm({ ...editForm, profile_photo: compressed });
      };
      reader.readAsDataURL(file);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-500"></div>
      </div>
    );
  }

  const avatarUrl = editForm.profile_photo || (user as any)?.profile_photo;

  return (
    <div className="min-h-screen bg-gray-50 pt-32 pb-12 px-4 sm:px-6 lg:px-8 font-inter">
      {showSuccess && createPortal(
        <div className="fixed inset-0 z-[1000] flex items-center justify-center p-6 bg-black/40 backdrop-blur-sm animate-in fade-in duration-300">
          <div className="bg-white rounded-2xl w-full max-w-sm p-8 shadow-2xl flex flex-col items-center text-center transform transition-all scale-100">
            <div className="w-16 h-16 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center text-2xl mb-6">
              <i className="fas fa-check"></i>
            </div>
            <h3 className="text-xl font-bold text-gray-900 mb-2">Profile Updated</h3>
            <p className="text-gray-500 mb-6">Your changes have been saved successfully.</p>
            <button onClick={() => setShowSuccess(false)} className="w-full py-3 bg-gray-900 text-white rounded-xl font-semibold hover:bg-gray-800 transition-colors">
              Continue
            </button>
          </div>
        </div>, document.body
      )}

      <div className="max-w-7xl mx-auto">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left Column: Profile Card */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden sticky top-32">
              <div className="h-32 bg-gradient-to-r from-orange-400 to-rose-500"></div>
              <div className="px-6 pb-8">


                <div className="text-center mb-8">
                  <h2 className="text-2xl font-bold text-gray-900 mb-1">{user?.fullName}</h2>
                  <p className="text-sm font-medium text-orange-500 uppercase tracking-wider mb-4">{user?.role}</p>
                  <div className="flex items-center justify-center gap-2 text-gray-500 text-sm">
                    <i className="fas fa-envelope"></i>
                    <span>{user?.email}</span>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4 border-t border-gray-100 pt-6 mb-6">
                  <div className="text-center">
                    <span className="block text-xl font-bold text-gray-900">{regCount}</span>
                    <span className="text-xs text-gray-500 uppercase tracking-wide">Registry</span>
                  </div>
                  <div className="text-center border-l border-gray-100">
                    <span className="block text-xl font-bold text-emerald-600">{pastEvents.length}</span>
                    <span className="text-xs text-gray-500 uppercase tracking-wide">Completed</span>
                  </div>
                </div>

                {!isEditing && (
                  <button 
                    onClick={onLogout} 
                    className="w-full py-2.5 border border-gray-200 text-gray-600 rounded-xl font-medium hover:bg-gray-50 hover:text-rose-600 transition-colors text-sm flex items-center justify-center gap-2"
                  >
                    <i className="fas fa-sign-out-alt"></i> Sign Out
                  </button>
                )}
              </div>
            </div>
          </div>

          {/* Right Column: Details & Edit Form */}
          <div className="lg:col-span-2 space-y-6">
            {/* Personal Information Card */}
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
              <div className="px-6 py-5 border-b border-gray-100 flex justify-between items-center">
                <h3 className="text-lg font-bold text-gray-900">Personal Information</h3>
                {!isEditing && (
                  <button 
                    onClick={() => setIsEditing(true)} 
                    className="text-sm font-medium text-orange-600 hover:text-orange-700 flex items-center gap-1"
                  >
                    <i className="fas fa-pen"></i> Edit
                  </button>
                )}
              </div>
              
              <div className="p-6">
                {isEditing ? (
                  <form onSubmit={handleUpdate} className="space-y-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-gray-700">Full Name</label>
                        <input 
                          type="text" 
                          value={editForm.name} 
                          onChange={e => setEditForm({...editForm, name: e.target.value})} 
                          className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                          placeholder="Enter your full name"
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-gray-700">Email Address</label>
                        <input 
                          type="email" 
                          value={editForm.email} 
                          onChange={e => setEditForm({...editForm, email: e.target.value})} 
                          className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                          placeholder="Enter your email"
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-gray-700">Phone Number</label>
                        <input 
                          type="tel" 
                          value={editForm.phone} 
                          onChange={e => setEditForm({...editForm, phone: e.target.value})} 
                          className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                          placeholder="Enter your phone number"
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-gray-700">Role</label>
                        <select 
                          value={editForm.role} 
                          onChange={e => setEditForm({...editForm, role: e.target.value})} 
                          className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                        >
                          <option value="STUDENT">STUDENT</option>
                          <option value="COORDINATOR">COORDINATOR</option>
                          <option value="ADMIN">ADMIN</option>
                        </select>
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-gray-700">Department</label>
                        <input 
                          type="text" 
                          value={editForm.department} 
                          onChange={e => setEditForm({...editForm, department: e.target.value})} 
                          className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                          placeholder="e.g. CSE, IT, ECE, Others"
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-gray-700">Year</label>
                        <select 
                          value={editForm.year} 
                          onChange={e => setEditForm({...editForm, year: e.target.value})} 
                          className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                        >
                          <option value="">Select Year</option>
                          <option value="1st Year">1st Year</option>
                          <option value="2nd Year">2nd Year</option>
                          <option value="3rd Year">3rd Year</option>
                          <option value="4th Year">4th Year</option>
                          <option value="5th Year">5th Year</option>
                        </select>
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-gray-700">Section</label>
                        <input 
                          type="text" 
                          value={editForm.section} 
                          onChange={e => setEditForm({...editForm, section: e.target.value.toUpperCase()})} 
                          className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                          placeholder="e.g. A, B, C"
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium text-gray-700">Registration Number</label>
                        <input 
                          type="text" 
                          value={editForm.regNo} 
                          onChange={e => setEditForm({...editForm, regNo: e.target.value.toUpperCase()})} 
                          className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                          placeholder="Enter Registration Number"
                        />
                      </div>
                      {editForm.department === 'Others' && (
                        <>
                          <div className="space-y-2">
                            <label className="text-sm font-medium text-gray-700">College Name</label>
                            <input 
                              type="text" 
                              value={editForm.collegeName} 
                              onChange={e => setEditForm({...editForm, collegeName: e.target.value})} 
                              className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                              placeholder="Enter College Name"
                            />
                          </div>
                          <div className="space-y-2">
                            <label className="text-sm font-medium text-gray-700">College Location</label>
                            <input 
                              type="text" 
                              value={editForm.collegeLocation} 
                              onChange={e => setEditForm({...editForm, collegeLocation: e.target.value})} 
                              className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                              placeholder="Enter College Location"
                            />
                          </div>
                          <div className="space-y-2">
                            <label className="text-sm font-medium text-gray-700">Class / Dept</label>
                            <input 
                              type="text" 
                              value={editForm.class} 
                              onChange={e => setEditForm({...editForm, class: e.target.value})} 
                              className="w-full px-4 py-2.5 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-orange-500/20 focus:border-orange-500 outline-none transition-all"
                              placeholder="Enter Class / Dept"
                            />
                          </div>
                        </>
                      )}
                    </div>
                    
                    {errorMessage && (
                      <div className="p-3 bg-rose-50 text-rose-600 text-sm rounded-lg flex items-center gap-2">
                        <i className="fas fa-exclamation-circle"></i>
                        {errorMessage}
                      </div>
                    )}

                    <div className="flex items-center gap-4 pt-4">
                      <button 
                        type="submit" 
                        disabled={isSaving}
                        className="px-6 py-2.5 bg-gray-900 text-white rounded-xl font-medium hover:bg-black transition-colors disabled:opacity-50 flex items-center gap-2"
                      >
                        {isSaving ? <i className="fas fa-spinner fa-spin"></i> : <i className="fas fa-save"></i>}
                        {isSaving ? 'Saving...' : 'Save Changes'}
                      </button>
                      <button 
                        type="button" 
                        onClick={() => { setIsEditing(false); setErrorMessage(null); }} 
                        className="px-6 py-2.5 bg-white border border-gray-200 text-gray-700 rounded-xl font-medium hover:bg-gray-50 transition-colors"
                      >
                        Cancel
                      </button>
                    </div>
                  </form>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-y-8 gap-x-12">
                    <div>
                      <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Full Name</label>
                      <p className="text-base font-semibold text-gray-900">{user?.fullName}</p>
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Email Address</label>
                      <p className="text-base font-semibold text-gray-900">{user?.email}</p>
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Phone Number</label>
                      <p className="text-base font-semibold text-gray-900">{user?.phone || 'Not provided'}</p>
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Role</label>
                      <p className="text-base font-semibold text-gray-900 flex items-center gap-2">
                        <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
                        {user?.role}
                      </p>
                    </div>
                    {user?.department === 'Others' ? (
                      <>
                        {user.collegeName && (
                          <div>
                            <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">College Name</label>
                            <p className="text-base font-semibold text-gray-900">{user.collegeName}</p>
                          </div>
                        )}
                        {(user as any).collegeLocation && (
                          <div>
                            <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">College Location</label>
                            <p className="text-base font-semibold text-gray-900">{(user as any).collegeLocation}</p>
                          </div>
                        )}
                        {(user as any).class && (
                          <div>
                            <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Class / Dept</label>
                            <p className="text-base font-semibold text-gray-900">{(user as any).class}</p>
                          </div>
                        )}
                      </>
                    ) : (
                      user?.department && (
                        <div>
                          <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Department</label>
                          <p className="text-base font-semibold text-gray-900">{user.department}</p>
                        </div>
                      )
                    )}
                    {user?.year && (
                      <div>
                        <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Year</label>
                        <p className="text-base font-semibold text-gray-900">{user.year}</p>
                      </div>
                    )}
                    {user?.department !== 'Others' && user?.section && (
                      <div>
                        <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Section</label>
                        <p className="text-base font-semibold text-gray-900">{user.section}</p>
                      </div>
                    )}
                    {user?.regNo && (
                      <div>
                        <label className="block text-xs font-medium text-gray-500 uppercase tracking-wider mb-1">Registration Number</label>
                        <p className="text-base font-semibold text-gray-900">{user.regNo}</p>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* Recent Activity Card */}
            {!isEditing && (
              <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                <div className="px-6 py-5 border-b border-gray-100">
                  <h3 className="text-lg font-bold text-gray-900">Recent Activity</h3>
                </div>
                <div className="p-6">
                  {pastEvents.length > 0 ? (
                    <div className="space-y-6">
                      {pastEvents.map((pe, idx) => (
                        <div key={idx} className="flex items-start gap-5 p-4 rounded-2xl hover:bg-gray-50 transition-colors border border-transparent hover:border-gray-100 group">
                          <div className="w-12 h-12 rounded-2xl bg-orange-50 text-orange-500 flex items-center justify-center text-lg shrink-0 shadow-sm border border-orange-100 group-hover:scale-110 transition-transform">
                            <i className="fas fa-calendar-check"></i>
                          </div>
                          <div>
                            <p className="text-sm font-black text-gray-900 uppercase tracking-tight">{pe.events?.title || 'Unknown Event'}</p>
                            <p className="text-[10px] text-gray-500 mt-1 uppercase font-bold tracking-widest">{pe.events?.category} • Completed on {new Date(pe.participation_date).toLocaleDateString()}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-center py-12 text-gray-400">
                      <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4 border border-gray-100">
                        <i className="fas fa-history text-2xl opacity-20"></i>
                      </div>
                      <p className="text-xs font-black uppercase tracking-widest text-gray-400">No participation history yet</p>
                      <p className="text-[10px] text-gray-400 mt-2 font-medium">Events you participate in will appear here.</p>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProfileView;
