import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { createTicketSchema, type CreateTicketInput } from '../../../shared/schemas/ticket';
import Modal from '../components/Modal';
import CTISelect from '../components/CTISelect';
import { useUsers, useCreateTicket } from '../api/queries';

interface NewTicketModalProps {
  onClose: () => void;
}

export default function NewTicketModal({ onClose }: NewTicketModalProps) {
  const navigate = useNavigate();
  const { data: users = [] } = useUsers();
  const createTicket = useCreateTicket();
  const [error, setError] = useState('');

  const {
    register,
    handleSubmit,
    control,
    formState: { errors, isSubmitting },
  } = useForm<CreateTicketInput>({
    resolver: zodResolver(createTicketSchema),
    defaultValues: {
      title: '',
      overview: '',
      severity: 3,
      categoryId: '',
      typeId: '',
      itemId: '',
      assigneeId: undefined,
    },
  });

  const onSubmit = async (data: CreateTicketInput) => {
    setError('');
    try {
      const { assigneeId, ...rest } = data;
      const created = await createTicket.mutateAsync(
        assigneeId ? { ...rest, assigneeId } : rest,
      );
      onClose();
      navigate(`/${created.displayId}`);
    } catch {
      setError('Failed to create ticket');
    }
  };

  const inputClass =
    'w-full bg-gray-800 border border-gray-700 text-gray-100 placeholder-gray-500 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent';
  const labelClass = 'block text-sm font-medium text-gray-300 mb-1';
  const errorClass = 'mt-1 text-xs text-red-400';

  return (
    <Modal title="New Ticket" onClose={onClose} size="lg">
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
        {error && (
          <div className="bg-red-500/10 border border-red-500/30 text-red-400 text-sm px-4 py-3 rounded-lg">
            {error}
          </div>
        )}

        <div>
          <label className={labelClass}>Title</label>
          <input
            type="text"
            className={inputClass}
            placeholder="Brief description of the issue"
            autoFocus
            {...register('title')}
          />
          {errors.title && <p className={errorClass}>{errors.title.message}</p>}
        </div>

        <div>
          <label className={labelClass}>Overview</label>
          <textarea
            rows={4}
            className={inputClass}
            placeholder="Detailed description... Markdown supported"
            {...register('overview')}
          />
          {errors.overview && <p className={errorClass}>{errors.overview.message}</p>}
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label className={labelClass}>Severity</label>
            <select
              className={inputClass}
              {...register('severity', { valueAsNumber: true })}
            >
              <option value={1}>SEV 1 — Critical</option>
              <option value={2}>SEV 2 — High</option>
              <option value={3}>SEV 3 — Medium</option>
              <option value={4}>SEV 4 — Low</option>
              <option value={5}>SEV 5 — Minimal</option>
            </select>
            {errors.severity && <p className={errorClass}>{errors.severity.message}</p>}
          </div>

          <div>
            <label className={labelClass}>Assignee</label>
            <select className={inputClass} {...register('assigneeId')}>
              <option value="">Unassigned</option>
              {users.map((u) => (
                <option key={u.id} value={u.id}>
                  {u.displayName}
                </option>
              ))}
            </select>
          </div>
        </div>

        <div>
          <label className={labelClass}>Routing (CTI)</label>
          <Controller
            control={control}
            name="categoryId"
            render={({ field: categoryField }) => (
              <Controller
                control={control}
                name="typeId"
                render={({ field: typeField }) => (
                  <Controller
                    control={control}
                    name="itemId"
                    render={({ field: itemField }) => (
                      <CTISelect
                        value={{
                          categoryId: categoryField.value,
                          typeId: typeField.value,
                          itemId: itemField.value,
                        }}
                        onChange={(cti) => {
                          categoryField.onChange(cti.categoryId);
                          typeField.onChange(cti.typeId);
                          itemField.onChange(cti.itemId);
                        }}
                      />
                    )}
                  />
                )}
              />
            )}
          />
          {(errors.categoryId || errors.typeId || errors.itemId) && (
            <p className={errorClass}>Please select a Category, Type, and Item</p>
          )}
        </div>

        <div className="flex justify-end gap-3 pt-1">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 text-sm text-gray-400 border border-gray-700 rounded-lg hover:bg-gray-800 transition-colors"
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={isSubmitting}
            className="px-4 py-2 text-sm bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 transition-colors"
          >
            {isSubmitting ? 'Creating...' : 'Create Ticket'}
          </button>
        </div>
      </form>
    </Modal>
  );
}
