/**
 * Edit User Page
 * Edit user information (Managers & Admins only, or own profile)
 */

'use client';

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

const userSchema = z.object({
  username: z.string().min(3, 'Username must be at least 3 characters'),
  email: z.string().email('Invalid email address').optional().or(z.literal('')),
  full_name: z.string().min(1, 'Full name is required'),
  role: z.enum(['cashier', 'manager', 'system_admin']),
  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('')),
  active: z.boolean(),
  password: z.string().min(6, 'Password must be at least 6 characters').optional().or(z.literal('')),
}).refine((data) => {
  // If password is provided, it must be at least 6 characters
  if (data.password && data.password !== '') {
    return data.password.length >= 6;
  }
  return true;
});

export default function EditUserPage() {
  const router = useRouter();
  const params = useParams();
  const userId = parseInt(params.id);
  const { user: currentUser } = useAuth();
  const queryClient = useQueryClient();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const isManagerOrAdmin = currentUser?.role === 'manager' || currentUser?.role === 'system_admin';
  const isOwnProfile = currentUser?.id === userId;

  // Fetch user details
  const { data: user, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: async () => {
      if (isNaN(userId)) {
        throw new Error('Invalid user ID');
      }
      const response = await usersAPI.getById(userId);
      return response?.data?.user || response?.data || response;
    },
    enabled: !isNaN(userId) && (isManagerOrAdmin || isOwnProfile),
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: zodResolver(userSchema),
    defaultValues: {
      username: '',
      email: '',
      full_name: '',
      role: 'cashier',
      pin_code: '',
      active: true,
      password: '',
    },
  });

  // Update form when user data loads
  useEffect(() => {
    if (user) {
      reset({
        username: user.username || '',
        email: user.email || '',
        full_name: user.full_name || '',
        role: user.role || 'cashier',
        pin_code: '',
        active: user.active !== undefined ? user.active : true,
        password: '',
      });
    }
  }, [user, reset]);

  const updateUserMutation = useMutation({
    mutationFn: async (data) => {
      const updateData = {
        username: data.username,
        full_name: data.full_name,
        role: data.role,
        active: data.active,
        ...(data.email && data.email !== '' && { email: data.email }),
        ...(data.password && data.password !== '' && { password: data.password }),
        ...(data.pin_code && data.pin_code !== '' && { pin_code: data.pin_code }),
      };
      return await usersAPI.update(userId, updateData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['users']);
      queryClient.invalidateQueries(['user', userId]);
      toast.success('User updated successfully!');
      router.push(`/settings/users/${userId}`);
    },
    onError: (error) => {
      const message = error?.response?.data?.message || error.message || 'Failed to update user';
      toast.error(message);
    },
    onSettled: () => {
      setIsSubmitting(false);
    },
  });

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

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

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

  if (!user) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>User not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  // If editing own profile, redirect to profile settings
  if (isOwnProfile) {
    router.push('/settings/profile');
    return <LoadingPage message="Redirecting..." />;
  }

  if (!isManagerOrAdmin) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Access denied. You can only edit your own profile.</p>
        <Button onClick={() => router.push('/settings/profile')} className="mt-4">
          Go to Profile
        </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 User Details
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Edit User</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">
                    Username *
                  </label>
                  <Input
                    {...register('username')}
                    placeholder="Enter username"
                    error={errors.username?.message}
                  />
                </div>

                <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 full name"
                    error={errors.full_name?.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>

            {/* Role and Status */}
            <div>
              <h3 className="text-lg font-semibold mb-4">Role & Status</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">
                    Role *
                  </label>
                  <select
                    {...register('role')}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                    error={errors.role?.message}
                  >
                    <option value="cashier">Cashier</option>
                    <option value="manager">Manager</option>
                    <option value="system_admin">System Admin</option>
                  </select>
                  {errors.role && (
                    <p className="text-sm text-red-600 mt-1">{errors.role.message}</p>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Status
                  </label>
                  <select
                    {...register('active', { valueAsBoolean: true })}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-800 dark:border-gray-600 dark:text-white"
                  >
                    <option value="true">Active</option>
                    <option value="false">Inactive</option>
                  </select>
                </div>
              </div>
            </div>

            {/* Change Password */}
            <div>
              <h3 className="text-lg font-semibold mb-4">Change Password</h3>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  New Password
                </label>
                <Input
                  type="password"
                  {...register('password')}
                  placeholder="Leave blank to keep current password"
                  error={errors.password?.message}
                />
                <p className="text-xs text-gray-500 mt-1">Leave blank if not changing password</p>
              </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 (leave blank to keep current)"
                  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>
  );
}

