import { useState } from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { trpc } from '@/trpc/client';
import { Button } from '@/components/ui/button';

const validationSchema = Yup.object({
  name: Yup.string()
    .min(2, 'Name must be at least 2 characters')
    .required('Name is required'),
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .required('Password is required'),
  roleId: Yup.number()
    .required('Role is required'),
});

interface StaffUserFormProps {
  onSuccess?: () => void;
}

export function StaffUserForm({ onSuccess }: StaffUserFormProps) {
  const createStaffMutation = trpc.admin.staffUser.createStaffUser.useMutation({
    onSuccess: (data) => {
      alert(`Staff user "${data.user.name}" created successfully!`);
      onSuccess?.();
    },
    onError: (error: any) => {
      alert(`Error: ${error.message}`);
    }
  });

  // Fetch available roles
  const { data: rolesData } = trpc.admin.staffUser.getRoles.useQuery();

  // Filter out super_admin role from dropdown
  const availableRoles = rolesData?.roles?.filter(role => role.name !== 'super_admin') || [];

  return (
    <div className="bg-gray-50 p-6 rounded-lg">
      <h3 className="text-lg font-semibold mb-4">Add New Staff User</h3>

      <Formik
        initialValues={{ name: '', password: '', roleId: '' }}
        validationSchema={validationSchema}
        onSubmit={(values, { resetForm }) => {
          createStaffMutation.mutate({
            name: values.name,
            password: values.password,
            roleId: parseInt(values.roleId),
          });
          resetForm();
        }}
      >
        {({ isSubmitting }) => (
          <Form className="space-y-4">
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                Name
              </label>
              <Field
                id="name"
                name="name"
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
              <ErrorMessage name="name" component="div" className="text-red-500 text-sm mt-1" />
            </div>

            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
                Password
              </label>
              <Field
                id="password"
                name="password"
                type="password"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
              <ErrorMessage name="password" component="div" className="text-red-500 text-sm mt-1" />
            </div>

            <div>
              <label htmlFor="roleId" className="block text-sm font-medium text-gray-700 mb-1">
                Role
              </label>
              <Field
                id="roleId"
                name="roleId"
                as="select"
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">Select a role</option>
                {availableRoles.map((role) => (
                  <option key={role.id} value={role.id}>
                    {role.name}
                  </option>
                ))}
              </Field>
              <ErrorMessage name="roleId" component="div" className="text-red-500 text-sm mt-1" />
            </div>

            <Button
              type="submit"
              className="w-full"
              disabled={isSubmitting || createStaffMutation.isPending}
            >
              {createStaffMutation.isPending ? 'Creating...' : 'Create Staff User'}
            </Button>
          </Form>
        )}
      </Formik>
    </div>
  );
}