'use client';

import { useState, useEffect, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useAuthStore } from '@/stores/auth-store';
import { userApi, type UserProfile, type UpdateUserProfileDto } from '@/services/api/user.api';
import { useTranslations } from 'next-intl';

/**
 * EN: Create profile schema with translated messages
 * VI: Tạo profile schema với thông báo đã dịch
 */
function createProfileSchema(
  t: (key: string, values?: Record<string, any>) => string
) {
  return z.object({
    firstName: z
      .string()
      .max(255, t('validation.maxLength', { max: 255 }))
      .optional(),
    lastName: z
      .string()
      .max(255, t('validation.maxLength', { max: 255 }))
      .optional(),
    phone: z
      .string()
      .max(20, t('validation.maxLength', { max: 20 }))
      .optional(),
    bio: z
      .string()
      .max(500, t('validation.maxLength', { max: 500 }))
      .optional(),
  });
}

/**
 * EN: User Profile page component
 * VI: Component trang Profile người dùng
 *
 * Features:
 * - Avatar upload with preview
 * - Profile fields (First Name, Last Name, Phone, Bio)
 * - Email display with verified status
 * - Username display
 * - Save changes button
 * - Loading states
 * - Error handling
 */
export default function ProfilePage() {
  // EN: Translation hook / VI: Hook translation
  const t = useTranslations();
  const { user } = useAuthStore();
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const fileInputRef = useRef<HTMLInputElement>(null);

  // EN: Create schema with translations / VI: Tạo schema với translations
  const profileSchema = createProfileSchema(t);
  type ProfileFormData = z.infer<typeof profileSchema>;

  const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
    reset,
    setValue,
  } = useForm<ProfileFormData>({
    resolver: zodResolver(profileSchema),
    defaultValues: {
      firstName: '',
      lastName: '',
      phone: '',
      bio: '',
    },
  });

  // EN: Fetch user profile on mount / VI: Lấy profile người dùng khi mount
  useEffect(() => {
    const fetchProfile = async () => {
      if (!user?.id) return;

      try {
        setIsLoading(true);
        const response = await userApi.getProfile(user.id);
        
        if (response.success && response.data) {
          setProfile(response.data);
          setValue('firstName', response.data.firstName || '');
          setValue('lastName', response.data.lastName || '');
          setValue('phone', response.data.phone || '');
          setValue('bio', (response.data.customFields?.bio as string) || '');
          
          if (response.data.avatarUrl) {
            setAvatarPreview(response.data.avatarUrl);
          }
        }
      } catch (error) {
        console.error('Failed to fetch profile:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchProfile();
  }, [user?.id, setValue]);

  // EN: Handle avatar file selection / VI: Xử lý chọn file avatar
  const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // EN: Validate file type / VI: Kiểm tra loại file
    if (!file.type.startsWith('image/')) {
      alert(t('settings.profile.selectImageFile'));
      return;
    }

    // EN: Validate file size (max 5MB) / VI: Kiểm tra kích thước file (tối đa 5MB)
    if (file.size > 5 * 1024 * 1024) {
      alert(t('settings.profile.imageSizeLimit'));
      return;
    }

    setAvatarFile(file);

    // EN: Create preview URL / VI: Tạo URL preview
    const reader = new FileReader();
    reader.onloadend = () => {
      setAvatarPreview(reader.result as string);
    };
    reader.readAsDataURL(file);
  };

  // EN: Handle avatar upload / VI: Xử lý upload avatar
  const handleAvatarUpload = async () => {
    if (!user?.id || !avatarFile) return;

    try {
      // EN: In a real implementation, you would upload the file to a storage service
      // and get the URL. For now, we'll use a data URL as placeholder.
      // VI: Trong implementation thực tế, bạn sẽ upload file lên storage service
      // và lấy URL. Hiện tại, chúng ta sẽ sử dụng data URL làm placeholder.
      
      // EN: TODO: Implement actual file upload to storage service
      // VI: TODO: Implement upload file thực tế lên storage service
      const avatarUrl = avatarPreview || '';

      const response = await userApi.uploadAvatar(user.id, avatarUrl);
      
      if (response.success && response.data) {
        setProfile(response.data);
        setAvatarFile(null);
        alert(t('settings.profile.uploadSuccess'));
      }
    } catch (error) {
      console.error('Failed to upload avatar:', error);
      alert(t('settings.profile.failedToUpload'));
    }
  };

  // EN: Handle form submission / VI: Xử lý submit form
  const onSubmit = async (data: ProfileFormData) => {
    if (!user?.id) return;

    try {
      setIsSaving(true);
      setSaveStatus('idle');

      const updateData: UpdateUserProfileDto = {
        firstName: data.firstName || undefined,
        lastName: data.lastName || undefined,
        phone: data.phone || undefined,
        customFields: {
          ...(profile?.customFields as Record<string, any> || {}),
          bio: data.bio || undefined,
        },
      };

      const response = await userApi.updateProfile(user.id, updateData);

      if (response.success && response.data) {
        setProfile(response.data);
        reset(data);
        setSaveStatus('success');
        
        // EN: Auto-hide success message after 3 seconds / VI: Tự động ẩn thông báo thành công sau 3 giây
        setTimeout(() => setSaveStatus('idle'), 3000);
      } else {
        setSaveStatus('error');
      }
    } catch (error) {
      console.error('Failed to update profile:', error);
      setSaveStatus('error');
    } finally {
      setIsSaving(false);
    }
  };

  // EN: Get user initials for avatar fallback / VI: Lấy chữ cái đầu cho avatar fallback
  const getUserInitials = () => {
    if (!user) return 'U';
    const firstName = profile?.firstName || user.email.split('@')[0];
    const lastName = profile?.lastName || '';
    return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase() || 'U';
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-accent-primary border-r-transparent"></div>
          <p className="mt-4 text-sm text-text-tertiary">
            {t('common.loading')}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="text-center py-12">
        <h2 className="text-2xl font-bold">Profile Settings</h2>
        <p className="text-muted-foreground mt-2">Profile form temporarily disabled during migration.</p>
      </div>
    </div>
  );
}
