import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { profileSchema, ProfileFormData } from '../schemas/profileSchema';
import { updateProfile, UpdateProfileRequest } from '../services/profileService';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useState } from 'react';
import { useAuthStore } from '@/stores/auth';
import { cn } from '@/lib/utils';
import { AvatarUpload } from './AvatarUpload';

interface ProfileEditFormProps {
  initialData: Partial<ProfileFormData>;
  onSuccess?: () => void;
  onCancel?: () => void;
}

export function ProfileEditForm({ initialData, onSuccess, onCancel }: ProfileEditFormProps) {
  const { user, refreshUser } = useAuthStore();
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string | null>(user?.avatar_url || null);
  
  const { 
    register, 
    handleSubmit, 
    formState: { errors, isSubmitting },
    watch,
    setValue,
  } = useForm<ProfileFormData>({
    resolver: zodResolver(profileSchema),
    defaultValues: {
      first_name: initialData.first_name || '',
      last_name: initialData.last_name || '',
      username: initialData.username || '',
      bio: initialData.bio || '',
      location: initialData.location || '',
      birthdate: initialData.birthdate || '',
      gender: initialData.gender,
    },
  });

  const genderValue = watch('gender');
  
  const onSubmit = async (data: ProfileFormData) => {
    if (!user?.id) {
      setError('User not authenticated');
      return;
    }

    setError(null);
    setSuccess(false);

    try {
      // Convert empty strings to undefined for optional fields
      const updateData: UpdateProfileRequest = {};
      
      if (data.first_name && data.first_name.trim() !== '') {
        updateData.first_name = data.first_name.trim();
      }
      if (data.last_name && data.last_name.trim() !== '') {
        updateData.last_name = data.last_name.trim();
      }
      if (data.username && data.username.trim() !== '') {
        updateData.username = data.username.trim();
      }
      if (data.bio && data.bio.trim() !== '') {
        updateData.bio = data.bio.trim();
      }
      if (data.location && data.location.trim() !== '') {
        updateData.location = data.location.trim();
      }
      if (data.birthdate && data.birthdate.trim() !== '') {
        updateData.birthdate = data.birthdate.trim();
      }
      if (data.gender) {
        updateData.gender = data.gender;
      }

      await updateProfile(user.id, updateData);
      setSuccess(true);
      
      // Refresh user data to get updated avatar
      await refreshUser();
      
      // Call onSuccess callback after a short delay
      setTimeout(() => {
        onSuccess?.();
      }, 1000);
    } catch (err: any) {
      const errorMessage = err.response?.data?.error || err.message || 'Failed to update profile';
      setError(errorMessage);
    }
  };

  const genderOptions = [
    { value: 'Male', label: 'Male' },
    { value: 'Female', label: 'Female' },
    { value: 'Other', label: 'Other' },
    { value: 'Prefer not to say', label: 'Prefer not to say' },
  ];

  const handleAvatarUpdated = async (newAvatarUrl: string) => {
    setAvatarUrl(newAvatarUrl);
    await refreshUser();
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      {error && (
        <Alert variant="destructive">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}
      
      {success && (
        <Alert>
          <AlertDescription>Profile updated successfully!</AlertDescription>
        </Alert>
      )}

      {/* Avatar Upload Section */}
      {user?.id && (
        <div className="flex flex-col items-center gap-4 pb-4 border-b">
          <Label>Avatar</Label>
          <AvatarUpload
            userId={user.id}
            currentAvatarUrl={avatarUrl || undefined}
            onAvatarUpdated={handleAvatarUpdated}
          />
        </div>
      )}

      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label htmlFor="first_name">First Name</Label>
          <Input
            id="first_name"
            {...register('first_name')}
            placeholder="First name"
            className={errors.first_name ? 'border-destructive' : ''}
          />
          {errors.first_name && (
            <p className="text-sm text-destructive">{errors.first_name.message}</p>
          )}
        </div>

        <div className="space-y-2">
          <Label htmlFor="last_name">Last Name</Label>
          <Input
            id="last_name"
            {...register('last_name')}
            placeholder="Last name"
            className={errors.last_name ? 'border-destructive' : ''}
          />
          {errors.last_name && (
            <p className="text-sm text-destructive">{errors.last_name.message}</p>
          )}
        </div>
      </div>

      <div className="space-y-2">
        <Label htmlFor="username">Username</Label>
        <Input
          id="username"
          {...register('username')}
          placeholder="Username"
          className={errors.username ? 'border-destructive' : ''}
        />
        {errors.username && (
          <p className="text-sm text-destructive">{errors.username.message}</p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="bio">Bio</Label>
        <textarea
          id="bio"
          {...register('bio')}
          placeholder="Tell us about yourself..."
          maxLength={500}
          rows={4}
          className={cn(
            'flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
            errors.bio ? 'border-destructive' : ''
          )}
        />
        {errors.bio && (
          <p className="text-sm text-destructive">{errors.bio.message}</p>
        )}
        <p className="text-xs text-muted-foreground">
          {watch('bio')?.length || 0}/500 characters
        </p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="location">Location</Label>
        <Input
          id="location"
          {...register('location')}
          placeholder="Location"
          className={errors.location ? 'border-destructive' : ''}
        />
        {errors.location && (
          <p className="text-sm text-destructive">{errors.location.message}</p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="birthdate">Birthdate</Label>
        <Input
          id="birthdate"
          type="date"
          {...register('birthdate')}
          className={errors.birthdate ? 'border-destructive' : ''}
        />
        {errors.birthdate && (
          <p className="text-sm text-destructive">{errors.birthdate.message}</p>
        )}
        <p className="text-xs text-muted-foreground">Must be at least 13 years old</p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="gender">Gender</Label>
        <Select
          options={genderOptions}
          value={genderValue || ''}
          onChange={(value) => {
            const genderValue = value === '' ? undefined : (value as ProfileFormData['gender']);
            setValue('gender', genderValue);
          }}
          placeholder="Select gender..."
        />
        {errors.gender && (
          <p className="text-sm text-destructive">{errors.gender.message}</p>
        )}
      </div>

      <div className="flex space-x-2 pt-4">
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting ? 'Saving...' : 'Save Profile'}
        </Button>
        {onCancel && (
          <Button type="button" variant="outline" onClick={onCancel} disabled={isSubmitting}>
            Cancel
          </Button>
        )}
      </div>
    </form>
  );
}

