'use client';

import { useMemo, useState } from 'react';
import { useSession } from 'next-auth/react';
import { useMutation, useSuspenseQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Icons } from '@/components/icons';
import { Button } from '@/components/ui/button';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle
} from '@/components/ui/sheet';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import { isSuperAdmin } from '@/lib/auth/roles';
import { createUserMutation, updateUserMutation } from '../api/mutations';
import { userMasterOptionsQueryOptions } from '../api/queries';
import type { User } from '../api/types';
import { type UserFormValues, userSchema } from '../schemas/user';
import { ROLE_OPTIONS } from './users-table/options';

interface UserFormSheetProps {
  user?: User;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function UserFormSheet({ user, open, onOpenChange }: UserFormSheetProps) {
  const { data: session } = useSession();
  const canChooseOrganizer = isSuperAdmin(session?.user.systemRole);
  const { data: masterOptions } = useSuspenseQuery(userMasterOptionsQueryOptions());
  const organizationOptions = useMemo(
    () =>
      (session?.user.organizations ?? []).map((organization) => ({
        value: organization.id,
        label: organization.name
      })),
    [session?.user.organizations]
  );

  const isEdit = !!user;

  const createMutation = useMutation({
    ...createUserMutation,
    onSuccess: (data) => {
      toast.success(data.message ?? 'User saved successfully');
      onOpenChange(false);
      form.reset();
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to save user');
    }
  });

  const updateMutation = useMutation({
    ...updateUserMutation,
    onSuccess: (data) => {
      toast.success(data.message ?? 'User updated successfully');
      onOpenChange(false);
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to update user');
    }
  });

  const form = useAppForm({
    defaultValues: {
      full_name: user?.full_name ?? '',
      username: user?.username ?? '',
      employee_code: user?.employee_code ?? '',
      email: user?.email ?? '',
      password: '',
      department_id: user?.department_id ? String(user.department_id) : '',
      position_id: user?.position_id ? String(user.position_id) : '',
      organization_id: user?.organization_id ?? session?.user.activeOrganizationId ?? undefined,
      organization_role: user?.organization_role ?? 'user',
      is_active: user ? user.status === 'Active' : true
    } as UserFormValues,
    validators: {
      onSubmit: userSchema
    },
    onSubmit: async ({ value }) => {
      if (isEdit && user) {
        await updateMutation.mutateAsync({ id: user.id, values: value });
        return;
      }

      await createMutation.mutateAsync(value);
    }
  });

  const { FormTextField, FormSelectField, FormSwitchField } = useFormFields<UserFormValues>();
  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className='flex flex-col'>
        <SheetHeader>
          <SheetTitle>{isEdit ? 'Edit User' : 'New User'}</SheetTitle>
          <SheetDescription>
            {isEdit
              ? 'Update organizer access and account details.'
              : 'Create a user account or add the selected organizer to an existing email.'}
          </SheetDescription>
        </SheetHeader>

        <div className='flex-1 overflow-auto'>
          <form.AppForm>
            <form.Form id='user-form-sheet' className='space-y-4'>
              <FormTextField
                name='full_name'
                label='Full Name'
                required
                placeholder='Jane Doe'
              />

              <FormTextField
                name='email'
                label='Email'
                required
                type='email'
                placeholder='jane@example.com'
              />

              <FormTextField
                name='username'
                label='Username'
                placeholder='jane.admin'
              />

              <FormTextField
                name='employee_code'
                label='Employee Code'
                placeholder='EMP-001'
              />

              <FormTextField
                name='password'
                label={isEdit ? 'New Password' : 'Password'}
                type='password'
                placeholder={isEdit ? 'Leave blank to keep current password' : 'Minimum 8 characters'}
              />

              <FormSelectField
                name='department_id'
                label='Department'
                options={masterOptions.departments}
                placeholder='Select department'
              />

              <FormSelectField
                name='position_id'
                label='Position'
                options={masterOptions.positions}
                placeholder='Select position'
              />

              {canChooseOrganizer && (
                <FormSelectField
                  name='organization_id'
                  label='Organizer'
                  required
                  options={organizationOptions}
                  placeholder='Select organizer'
                />
              )}

              <FormSelectField
                name='organization_role'
                label='Organizer Role'
                required
                options={canChooseOrganizer ? ROLE_OPTIONS : ROLE_OPTIONS.filter((role) => role.value === 'user')}
                placeholder='Select role'
              />

              <FormSwitchField
                name='is_active'
                label='Active Account'
                description='Inactive users cannot sign in.'
              />
            </form.Form>
          </form.AppForm>
        </div>

        <SheetFooter>
          <Button type='button' variant='outline' onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button type='submit' form='user-form-sheet' isLoading={isPending}>
            <Icons.check /> {isEdit ? 'Update User' : 'Save User'}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}

export function UserFormSheetTrigger() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <Button onClick={() => setOpen(true)}>
        <Icons.add className='mr-2 h-4 w-4' /> Add User
      </Button>
      <UserFormSheet open={open} onOpenChange={setOpen} />
    </>
  );
}
