
import React, { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useToast } from '@/hooks/useToast.wrapper';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/auth';

const profileFormSchema = z.object({
  name: z.string().min(2, {
    message: '이름은 2글자 이상이어야 합니다.',
  }),
  email: z.string().email({
    message: '유효한 이메일 주소를 입력해주세요.',
  }),
});

type ProfileFormValues = z.infer<typeof profileFormSchema>;

const ProfileForm = () => {
  const navigate = useNavigate();
  const { toast } = useToast();
  const { user } = useAuth();
  
  const form = useForm<ProfileFormValues>({
    resolver: zodResolver(profileFormSchema),
    defaultValues: {
      name: '',
      email: '',
    },
  });

  // 로그인된 사용자 정보로 폼 값 설정
  useEffect(() => {
    if (user) {
      form.reset({
        name: user.user_metadata?.username || '',
        email: user.email || '',
      });
    }
  }, [user, form]);

  const onSubmit = (data: ProfileFormValues) => {
    console.log('Form submitted:', data);
    // Here you would typically update the profile data
    // Show success message
    toast({
      title: "프로필 업데이트 완료",
      description: "프로필 정보가 성공적으로 업데이트되었습니다.",
    });
    navigate('/settings');
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 neuro-flat p-6 mb-6">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>이름</FormLabel>
              <FormControl>
                <Input placeholder="이름을 입력하세요" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>이메일</FormLabel>
              <FormControl>
                <Input placeholder="이메일을 입력하세요" {...field} readOnly />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        
        <div className="pt-4">
          <Button 
            type="submit" 
            className="w-full bg-neuro-income text-white hover:bg-neuro-income/90"
          >
            저장하기
          </Button>
        </div>
      </form>
    </Form>
  );
};

export default ProfileForm;
