/**
 * Profile Settings Page
 * User profile management (own profile only)
 */

'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useAuth } from '@/contexts/AuthContext';
import { authAPI } from '@/lib/api/auth';
import { usersAPI } from '@/lib/api/users';
import { Button, Card, CardHeader, CardTitle, CardContent, Input, LoadingPage } from '@/components/ui';
import { ArrowLeft, Eye, EyeOff } from 'lucide-react';
import toast from 'react-hot-toast';

const profileSchema = z.object({
  full_name: z.string().min(1, 'Full name is required'),
  email: z.string().email('Invalid email address').optional().or(z.literal('')),
  username: z.string().min(3, 'Username must be at least 3 characters'),
  current_password: z.string().optional(),
  new_password: z.string().min(6, 'Password must be at least 6 characters').optional().or(z.literal('')),
  confirm_password: z.string().optional(),
  pin_code: z.string().min(4, 'PIN code must be at least 4 digits').max(6, 'PIN code must be at most 6 digits').optional().or(z.literal('')),
}).refine((data) => {
  // If new_password is provided, confirm_password must match
  if (data.new_password && data.new_password !== '') {
    return data.new_password === data.confirm_password;
  }
  return true;
}, {
  message: 'Passwords do not match',
  path: ['confirm_password'],
});

export default function ProfileSettingsPage() {
  const router = useRouter();
  const { user, setUser } = useAuth();
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // Fetch current user profile
  const { data: profile, isLoading, error } = useQuery({
    queryKey: ['user-profile', user?.id],
    queryFn: async () => {
      if (!user?.id) return null;
      const response = await authAPI.getProfile();
      return response?.data?.user || response?.data || response;
    },
    enabled: !!user?.id,
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: zodResolver(profileSchema),
    defaultValues: {
      full_name: '',
      email: '',
      username: '',
      current_password: '',
      new_password: '',
      confirm_password: '',
      pin_code: '',
    },
  });

  // Update form when profile data loads
  useEffect(() => {
    if (profile) {
      reset({
        full_name: profile.full_name || '',
        email: profile.email || '',
        username: profile.username || '',
        current_password: '',
        new_password: '',
        confirm_password: '',
        pin_code: '',
      });
    }
  }, [profile, reset]);

  const updateProfileMutation = useMutation({
    mutationFn: async (data) => {
      const updateData = {
        full_name: data.full_name,
        email: data.email || undefined,
        username: data.username,
      };

      // Only include password if new_password is provided
      if (data.new_password && data.new_password !== '') {
        if (!data.current_password) {
          throw new Error('Current password is required to change password');
        }
        updateData.current_password = data.current_password;
        updateData.password = data.new_password;
      }

      // Only include PIN code if provided (empty string will clear it, but we'll send null to clear)
      if (data.pin_code !== undefined && data.pin_code !== '') {
        updateData.pin_code = data.pin_code;
      } else if (data.pin_code === '') {
        // Allow clearing PIN by sending empty string (backend will handle it)
        updateData.pin_code = '';
      }

      return await usersAPI.update(user.id, updateData);
    },
    onSuccess: (response) => {
      const updatedUser = response?.data?.user || response?.data || response;
      
      // Update auth context
      setUser(updatedUser);
      if (typeof window !== 'undefined') {
        localStorage.setItem('user', JSON.stringify(updatedUser));
      }
      
      queryClient.invalidateQueries(['user-profile', user?.id]);
      toast.success('Profile updated successfully!');
      
      // Reset password fields
      reset({
        ...updatedUser,
        current_password: '',
        new_password: '',
        confirm_password: '',
        pin_code: '',
      });
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to update profile';
      toast.error(message);
    },
    onSettled: () => {
      setIsSubmitting(false);
    },
  });

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    updateProfileMutation.mutate(data);
  };

  if (isLoading) {
    return <LoadingPage message="Loading profile..." />;
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Error loading profile: {error.message}</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 max-w-4xl">
      <div className="mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to Settings
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Profile Settings</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            {/* Basic Information */}
            <div>
              <h3 className="text-lg font-semibold mb-4">Basic Information</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Full Name *
                  </label>
                  <Input
                    {...register('full_name')}
                    placeholder="Enter your full name"
                    error={errors.full_name?.message}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Username *
                  </label>
                  <Input
                    {...register('username')}
                    placeholder="Enter username"
                    error={errors.username?.message}
                  />
                </div>

                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Email
                  </label>
                  <Input
                    type="email"
                    {...register('email')}
                    placeholder="Enter email address"
                    error={errors.email?.message}
                  />
                </div>
              </div>
            </div>

            {/* Change Password */}
            <div>
              <h3 className="text-lg font-semibold mb-4">Change Password</h3>
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Current Password
                  </label>
                  <div className="relative">
                    <Input
                      type={showCurrentPassword ? 'text' : 'password'}
                      {...register('current_password')}
                      placeholder="Enter current password"
                      error={errors.current_password?.message}
                    />
                    <button
                      type="button"
                      onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                    >
                      {showCurrentPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                    </button>
                  </div>
                  <p className="text-xs text-gray-500 mt-1">Leave blank if not changing password</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      New Password
                    </label>
                    <div className="relative">
                      <Input
                        type={showNewPassword ? 'text' : 'password'}
                        {...register('new_password')}
                        placeholder="Enter new password"
                        error={errors.new_password?.message}
                      />
                      <button
                        type="button"
                        onClick={() => setShowNewPassword(!showNewPassword)}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                      >
                        {showNewPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Confirm Password
                    </label>
                    <div className="relative">
                      <Input
                        type={showConfirmPassword ? 'text' : 'password'}
                        {...register('confirm_password')}
                        placeholder="Confirm new password"
                        error={errors.confirm_password?.message}
                      />
                      <button
                        type="button"
                        onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                      >
                        {showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* PIN Code */}
            <div>
              <h3 className="text-lg font-semibold mb-4">PIN Code (for quick POS login)</h3>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  PIN Code
                </label>
                <Input
                  type="text"
                  {...register('pin_code')}
                  placeholder="Enter 4-6 digit PIN code"
                  maxLength={6}
                  error={errors.pin_code?.message}
                />
                <p className="text-xs text-gray-500 mt-1">Leave blank if not changing PIN code</p>
              </div>
            </div>

            {/* Submit Button */}
            <div className="flex justify-end gap-4 pt-4 border-t">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.back()}
                disabled={isSubmitting}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="primary"
                disabled={isSubmitting}
                loading={isSubmitting}
              >
                Save Changes
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}

