'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 { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  CardFooter,
} from '@/components/ui/card';
import {
  Avatar,
  AvatarImage,
  AvatarFallback,
} from '@/components/ui/avatar';
import { Camera, CheckCircle2, XCircle } from 'lucide-react';
import { useTranslation } from '@/hooks/use-translation';

/**
 * 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 } = useTranslation();
  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">
      {/* EN: Profile header card / VI: Card header profile */}
      <Card>
        <CardHeader>
          <CardTitle>{t('settings.profile.title')}</CardTitle>
          <CardDescription>
            {t('settings.profile.updateInfo', { defaultValue: 'Update your profile information and avatar' })}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            {/* EN: Avatar section / VI: Phần avatar */}
            <div className="flex items-center gap-6">
              <div className="relative">
                <Avatar size="xl" className="h-24 w-24">
                  {avatarPreview && (
                    <AvatarImage src={avatarPreview} alt={t('settings.profile.title')} />
                  )}
                  <AvatarFallback>{getUserInitials()}</AvatarFallback>
                </Avatar>
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="absolute bottom-0 right-0 flex h-8 w-8 items-center justify-center rounded-full bg-accent-primary text-white shadow-md transition-all hover:brightness-110 hover:scale-110"
                  aria-label={t('settings.profile.uploadAvatar')}
                >
                  <Camera className="h-4 w-4" />
                </button>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  onChange={handleAvatarChange}
                  className="hidden"
                  aria-label={t('settings.profile.changeAvatar')}
                />
              </div>
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-[#FAFAFA]">
                  {profile?.firstName && profile?.lastName
                    ? `${profile.firstName} ${profile.lastName}`
                    : user?.email || t('common.user', { defaultValue: 'User' })}
                </h3>
                <p className="text-sm text-[#A0A0A0]">
                  {user?.email}
                  {(user as any)?.emailVerified && (
                    <span className="ml-2 inline-flex items-center gap-1 text-[#10B981]">
                      <CheckCircle2 className="h-3 w-3" />
                      <span className="text-xs">{t('settings.profile.verified')}</span>
                    </span>
                  )}
                </p>
                {avatarFile && (
                  <Button
                    type="button"
                    variant="secondary"
                    size="sm"
                    onClick={handleAvatarUpload}
                    className="mt-2"
                  >
                    {t('settings.profile.uploadAvatar')}
                  </Button>
                )}
              </div>
            </div>

            {/* EN: Form fields / VI: Các trường form */}
            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
              <Input
                label={t('settings.profile.firstName')}
                placeholder={t('settings.profile.enterFirstName', { defaultValue: 'Enter your first name' })}
                {...register('firstName')}
                errorMessage={errors.firstName?.message}
              />

              <Input
                label={t('settings.profile.lastName')}
                placeholder={t('settings.profile.enterLastName', { defaultValue: 'Enter your last name' })}
                {...register('lastName')}
                errorMessage={errors.lastName?.message}
              />
            </div>

            <Input
              label={t('settings.profile.email')}
              type="email"
              value={user?.email || ''}
              disabled
              helperText={t('settings.profile.emailCannotChange', { defaultValue: 'Email cannot be changed' })}
            />

            <Input
              label={t('settings.profile.username')}
              value={(user as any)?.username || t('settings.profile.notSet', { defaultValue: 'Not set' })}
              disabled
              helperText={t('settings.profile.usernameCannotChange', { defaultValue: 'Username cannot be changed' })}
            />

            <Input
              label={t('settings.profile.phone')}
              type="tel"
              placeholder={t('settings.profile.enterPhone', { defaultValue: 'Enter your phone number' })}
              {...register('phone')}
              errorMessage={errors.phone?.message}
            />

            <div>
              <label
                htmlFor="bio"
                className="block text-sm font-medium text-text-secondary mb-2"
              >
                {t('settings.profile.bio')}
              </label>
              <textarea
                id="bio"
                rows={4}
                placeholder={t('settings.profile.bioPlaceholder', { defaultValue: 'Tell us about yourself' })}
                {...register('bio')}
                className="flex w-full rounded-md border border-border-primary bg-bg-secondary px-3 py-2 text-base text-text-primary placeholder:text-text-tertiary transition-all duration-[150ms] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:border-accent-primary focus-visible:ring-accent-primary focus-visible:shadow-[0_0_20px_rgba(59,130,246,0.3)] disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-bg-tertiary"
              />
              {errors.bio && (
                <p className="mt-1.5 text-sm text-accent-error flex items-center gap-1">
                  <XCircle className="h-4 w-4" />
                  {errors.bio.message}
                </p>
              )}
            </div>

            {/* EN: Save status message / VI: Thông báo trạng thái lưu */}
            {saveStatus === 'success' && (
              <div className="rounded-lg bg-accent-success/10 border border-accent-success p-3 flex items-center gap-2 text-sm text-accent-success">
                <CheckCircle2 className="h-4 w-4" />
                <span>
                  {t('settings.profile.changesSaved')}
                </span>
              </div>
            )}

            {saveStatus === 'error' && (
              <div className="rounded-lg bg-accent-error/10 border border-accent-error p-3 flex items-center gap-2 text-sm text-accent-error">
                <XCircle className="h-4 w-4" />
                <span>
                  {t('settings.profile.failedToUpdate')}
                </span>
              </div>
            )}

            <CardFooter className="flex justify-end gap-3 px-0">
              <Button
                type="submit"
                variant="primary"
                loading={isSaving}
                disabled={!isDirty || isSaving}
              >
                {t('settings.profile.saveChanges')}
              </Button>
            </CardFooter>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
