'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Save } from 'lucide-react';
import { toast } from 'sonner';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { useEffect } from 'react';

import { adminUsersApi, type UpdateAdminUserRequest } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useAuthStore } from '@/store/auth';

const formSchema = z.object({
  email: z.string().email('Invalid email address'),
  password: z.string().min(8, 'Password must be at least 8 characters').optional().or(z.literal('')),
  first_name: z.string().max(100).optional(),
  last_name: z.string().max(100).optional(),
  role: z.enum(['admin', 'super_admin']).optional(),
  is_active: z.boolean().optional(),
});

type FormValues = z.infer<typeof formSchema>;

export default function EditAdminUserPage() {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const { user: currentUser } = useAuthStore();
  const adminUserId = Number(params.id);

  const isSuperAdmin = currentUser?.role === 'super_admin';
  const isSelf = currentUser?.id === adminUserId;

  const { data: adminUser, isLoading: isLoadingUser } = useQuery({
    queryKey: ['admin-user', adminUserId],
    queryFn: () => adminUsersApi.get(adminUserId),
    enabled: !!adminUserId,
  });

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: '',
      password: '',
      first_name: '',
      last_name: '',
      role: 'admin',
      is_active: true,
    },
  });

  useEffect(() => {
    if (adminUser) {
      form.reset({
        email: adminUser.email,
        password: '',
        first_name: adminUser.first_name || '',
        last_name: adminUser.last_name || '',
        role: adminUser.role,
        is_active: adminUser.is_active,
      });
    }
  }, [adminUser, form]);

  const updateMutation = useMutation({
    mutationFn: (data: UpdateAdminUserRequest) => adminUsersApi.update(adminUserId, data),
    onSuccess: () => {
      toast.success('Admin user updated successfully');
      queryClient.invalidateQueries({ queryKey: ['admin-users'] });
      queryClient.invalidateQueries({ queryKey: ['admin-user', adminUserId] });
      router.push(`/admin-users/${adminUserId}`);
    },
    onError: (error: Error & { response?: { data?: { error?: string } } }) => {
      toast.error(error.response?.data?.error || 'Failed to update admin user');
    },
  });

  const onSubmit = (values: FormValues) => {
    const data: UpdateAdminUserRequest = {};

    if (values.email !== adminUser?.email) {
      data.email = values.email;
    }
    if (values.password && values.password.length > 0) {
      data.password = values.password;
    }
    if (values.first_name !== adminUser?.first_name) {
      data.first_name = values.first_name;
    }
    if (values.last_name !== adminUser?.last_name) {
      data.last_name = values.last_name;
    }
    if (isSuperAdmin && values.role !== adminUser?.role) {
      data.role = values.role;
    }
    if (isSuperAdmin && values.is_active !== adminUser?.is_active) {
      data.is_active = values.is_active;
    }

    updateMutation.mutate(data);
  };

  if (isLoadingUser) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  if (!adminUser) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Admin user not found</div>
      </div>
    );
  }

  // Check permissions
  if (!isSuperAdmin && !isSelf) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">You do not have permission to edit this admin user</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" asChild>
          <Link href={`/admin-users/${adminUserId}`}>
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div>
          <h1 className="text-2xl font-bold">Edit Admin User</h1>
          <p className="text-muted-foreground">{adminUser.email}</p>
        </div>
      </div>

      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Account Details</CardTitle>
              <CardDescription>Update administrator account information</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Email</FormLabel>
                    <FormControl>
                      <Input type="email" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Password</FormLabel>
                    <FormControl>
                      <Input type="password" placeholder="Leave blank to keep current password" {...field} />
                    </FormControl>
                    <FormDescription>
                      Only fill this if you want to change the password
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="first_name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>First Name</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="last_name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Last Name</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {isSuperAdmin && (
                <>
                  <FormField
                    control={form.control}
                    name="role"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Role</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select a role" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="admin">Admin</SelectItem>
                            <SelectItem value="super_admin">Super Admin</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormDescription>
                          Super admins can manage other admin users
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="is_active"
                    render={({ field }) => (
                      <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                        <div className="space-y-0.5">
                          <FormLabel className="text-base">Active</FormLabel>
                          <FormDescription>
                            {isSelf
                              ? 'You cannot deactivate your own account'
                              : 'Inactive accounts cannot log in'
                            }
                          </FormDescription>
                        </div>
                        <FormControl>
                          <Switch
                            checked={field.value}
                            onCheckedChange={field.onChange}
                            disabled={isSelf}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                </>
              )}
            </CardContent>
          </Card>

          <div className="flex justify-end gap-4">
            <Button type="button" variant="outline" asChild>
              <Link href={`/admin-users/${adminUserId}`}>Cancel</Link>
            </Button>
            <Button type="submit" disabled={updateMutation.isPending}>
              <Save className="mr-2 h-4 w-4" />
              {updateMutation.isPending ? 'Saving...' : 'Save Changes'}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
