'use client';

import { useState, useRef, useEffect } from 'react';
import Image from 'next/image';
import { useSession, signIn } from 'next-auth/react';
import { uploadService } from '@/services/upload.service';
import { agentsService } from '@/services/agents.service';

interface ProfileSettingsFormProps {
  initialData?: {
    fullName: string;
    career: string;
    email: string;
    phone: string;
    location: string;
    avatar?: string;
  };
  onSave?: (data: {
    fullName: string;
    career: string;
    email: string;
    phone: string;
    location: string;
  }) => void;
  descriptionText?: string;
}

export function ProfileSettingsForm({
  initialData,
  onSave,
  descriptionText = 'This information will be displayed on your public profile page.',
}: ProfileSettingsFormProps) {
  const { data: session, update: updateSession } = useSession();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [formData, setFormData] = useState({
    fullName: initialData?.fullName || '',
    career: initialData?.career || '',
    email: initialData?.email || '',
    phone: initialData?.phone || '',
    location: initialData?.location || '',
  });

  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // Fetch profile data on mount
  useEffect(() => {
    const fetchProfile = async () => {
      try {
        setIsLoading(true);
        const profile = await agentsService.getMyProfile();

        setFormData({
          fullName: `${profile.firstName || ''} ${profile.lastName || ''}`.trim(),
          career: profile.agentType?.name || 'Real Estate Agent',
          email: profile.email || session?.user?.email || '',
          phone: profile.phone || '',
          location: profile.serviceAreas?.[0] || '',
        });

        // Handle avatar URL - if it's an S3 key, get presigned URL
        if (profile.avatar) {
          try {
            const presignedUrl = await uploadService.getPresignedDownloadUrl(profile.avatar);
            setAvatarUrl(presignedUrl);
          } catch {
            // If getting presigned URL fails, the avatar might be a full URL
            setAvatarUrl(profile.avatar);
          }
        }
      } catch (err) {
        console.error('Failed to fetch profile:', err);
        // Use session data as fallback
        if (session?.user) {
          setFormData(prev => ({
            ...prev,
            fullName: session.user?.name || prev.fullName,
            email: session.user?.email || prev.email,
          }));
          if (session.user.image) {
            setAvatarUrl(session.user.image);
          }
        }
      } finally {
        setIsLoading(false);
      }
    };

    if (session) {
      fetchProfile();
    }
  }, [session]);

  const handleChange = (field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    setError(null);
    setSuccessMessage(null);
  };

  const handleUploadClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // Validate file type
    const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!validTypes.includes(file.type)) {
      setError('Please upload a JPEG, PNG, or GIF image.');
      return;
    }

    // Validate file size (2MB max)
    const maxSize = 2 * 1024 * 1024;
    if (file.size > maxSize) {
      setError('File size must be less than 2MB.');
      return;
    }

    try {
      setIsUploading(true);
      setError(null);
      setUploadProgress(0);

      // Upload the avatar
      const uploadedFile = await uploadService.uploadAvatar(file, (progress) => {
        setUploadProgress(progress.percentage);
      });

      // Update the profile with the new avatar key
      await agentsService.updateProfile({ avatar: uploadedFile.url });

      // Get the presigned URL for display
      const presignedUrl = await uploadService.getPresignedDownloadUrl(uploadedFile.url);
      setAvatarUrl(presignedUrl);

      // Update the session to reflect the new avatar
      await updateSession({
        ...session,
        user: {
          ...session?.user,
          image: presignedUrl,
        },
      });

      setSuccessMessage('Profile picture updated successfully!');
    } catch (err) {
      console.error('Upload failed:', err);
      setError('Failed to upload profile picture. Please try again.');
    } finally {
      setIsUploading(false);
      setUploadProgress(0);
      // Reset file input
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleDeleteAvatar = async () => {
    try {
      setIsUploading(true);
      setError(null);

      // Update profile to remove avatar
      await agentsService.updateProfile({ avatar: null });
      setAvatarUrl(null);

      // Update session
      await updateSession({
        ...session,
        user: {
          ...session?.user,
          image: null,
        },
      });

      setSuccessMessage('Profile picture removed successfully!');
    } catch (err) {
      console.error('Delete failed:', err);
      setError('Failed to remove profile picture. Please try again.');
    } finally {
      setIsUploading(false);
    }
  };

  const handleSave = async () => {
    try {
      setIsSaving(true);
      setError(null);

      // Split full name into first and last name
      const nameParts = formData.fullName.trim().split(' ');
      const firstName = nameParts[0] || '';
      const lastName = nameParts.slice(1).join(' ') || '';

      // Update profile
      await agentsService.updateProfile({
        firstName,
        lastName,
        email: formData.email,
        phone: formData.phone,
        serviceAreas: formData.location ? [formData.location] : [],
      });

      // Update session with new name
      await updateSession({
        ...session,
        user: {
          ...session?.user,
          name: formData.fullName,
        },
      });

      if (onSave) {
        onSave(formData);
      }

      setSuccessMessage('Profile settings saved successfully!');
    } catch (err) {
      console.error('Save failed:', err);
      setError('Failed to save profile settings. Please try again.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    // Reset to initial data or session data
    if (session?.user) {
      setFormData(prev => ({
        ...prev,
        fullName: session.user?.name || prev.fullName,
        email: session.user?.email || prev.email,
      }));
    }
    setError(null);
    setSuccessMessage(null);
  };

  if (isLoading) {
    return (
      <div className="border border-[#00293d]/20 rounded-[15px] bg-white p-8 flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#e58625]"></div>
      </div>
    );
  }

  return (
    <div className="border border-[#00293d]/20 rounded-[15px] bg-white p-8">
      {/* Header */}
      <div className="mb-6">
        <h1 className="font-fractul font-bold text-[20px] leading-[24px] text-[#00293D] mb-2">
          Public Profile
        </h1>
        <p className="font-serif text-[13px] leading-[17px] text-[#00293D]/60">
          {descriptionText}
        </p>
      </div>

      {/* Error/Success Messages */}
      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-[10px] text-red-600 text-sm font-serif">
          {error}
        </div>
      )}
      {successMessage && (
        <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-[10px] text-green-600 text-sm font-serif">
          {successMessage}
        </div>
      )}

      {/* Profile Photo Section */}
      <div className="mb-8">
        <div className="flex items-start gap-4">
          <div className="w-[60px] h-[60px] rounded-full overflow-hidden border border-[#00293D]/20 flex-shrink-0 bg-gray-100">
            {avatarUrl ? (
              <img
                src={avatarUrl}
                alt="Profile"
                className="w-full h-full object-cover"
              />
            ) : (
              <Image
                src="/assets/icons/user-placeholder-icon.svg"
                alt="Profile"
                width={60}
                height={60}
                className="w-full h-full object-cover"
              />
            )}
          </div>
          <div>
            <p className="font-serif font-medium text-[14px] text-[#00293D] mb-2">
              Public Picture
            </p>
            <div className="flex items-center gap-2 mb-2">
              <input
                ref={fileInputRef}
                type="file"
                accept="image/jpeg,image/png,image/gif"
                onChange={handleFileChange}
                className="hidden"
              />
              <button
                onClick={handleUploadClick}
                disabled={isUploading}
                className="px-4 py-1.5 bg-[#e58625] text-white rounded-[20px] font-serif text-[12px] hover:bg-[#d47920] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isUploading ? `Uploading ${uploadProgress}%` : 'Upload Now'}
              </button>
              <button
                onClick={handleDeleteAvatar}
                disabled={isUploading || !avatarUrl}
                className="px-4 py-1.5 border border-[#00293D]/30 text-[#00293D] rounded-[20px] font-serif text-[12px] hover:bg-[#00293d]/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Delete
              </button>
            </div>
            <p className="font-serif text-[11px] text-[#00293D]/50">
              Supported formats: JPEG, PNG, GIF Max file size: 2MB
            </p>
          </div>
        </div>
      </div>

      {/* Form Fields */}
      <div className="space-y-5">
        {/* Row 1: Full Name & Career */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
          <div>
            <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
              Full Name
            </label>
            <input
              type="text"
              value={formData.fullName}
              onChange={(e) => handleChange('fullName', e.target.value)}
              className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]"
            />
          </div>
          <div>
            <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
              Career
            </label>
            <input
              type="text"
              value={formData.career}
              onChange={(e) => handleChange('career', e.target.value)}
              className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]"
            />
          </div>
        </div>

        {/* Row 2: Email & Phone */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
          <div>
            <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
              Email Address
            </label>
            <input
              type="email"
              value={formData.email}
              onChange={(e) => handleChange('email', e.target.value)}
              className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]"
            />
          </div>
          <div>
            <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
              Phone Number
            </label>
            <input
              type="tel"
              value={formData.phone}
              onChange={(e) => handleChange('phone', e.target.value)}
              className="w-full h-[44px] px-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]"
            />
          </div>
        </div>

        {/* Row 3: Location */}
        <div>
          <label className="block text-[12px] font-medium text-[#00293D]/70 font-serif mb-2">
            Location
          </label>
          <div className="relative">
            <div className="absolute left-4 top-1/2 -translate-y-1/2">
              <Image
                src="/assets/icons/location-icon.svg"
                alt="Location"
                width={16}
                height={16}
              />
            </div>
            <input
              type="text"
              value={formData.location}
              onChange={(e) => handleChange('location', e.target.value)}
              className="w-full sm:w-1/2 h-[44px] pl-10 pr-4 border border-[#00293D]/20 rounded-[10px] text-[14px] font-serif text-[#00293D] focus:outline-none focus:border-[#E58625]"
            />
          </div>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="mt-8 flex justify-end gap-3">
        <button
          onClick={handleCancel}
          disabled={isSaving}
          className="px-8 py-3 border border-[#00293D]/30 text-[#00293D] rounded-[10px] font-serif font-medium text-[14px] hover:bg-[#00293d]/5 transition-colors disabled:opacity-50"
        >
          Cancel
        </button>
        <button
          onClick={handleSave}
          disabled={isSaving}
          className="px-8 py-3 bg-[#e58625] text-white rounded-[10px] font-serif font-medium text-[14px] hover:bg-[#d47920] transition-colors disabled:opacity-50"
        >
          {isSaving ? 'Saving...' : 'Save Changes'}
        </button>
      </div>
    </div>
  );
}
