All files / src/components/features/support/SupportPortal NewTicketForm.tsx

0% Statements 0/268
100% Branches 0/0
0% Functions 0/1
0% Lines 0/268

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client';

/**
 * NewTicketForm - Form for creating a new support ticket
 */

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { clientLogger } from '@/lib/logging/clientLogger';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { CreateTicketSchema, CreateTicketInput } from '@/lib/validation/support-schemas';
import { TicketCategory, TicketPriority } from '@/types/support';
import { TICKET_CATEGORY_CONFIG, TICKET_PRIORITY_CONFIG } from '@/constants/support';
import { Icon } from '@/components/ui/icons';

export interface NewTicketFormProps {
  /** Pre-filled customer email */
  defaultEmail?: string;
  /** Pre-filled customer name */
  defaultName?: string;
  /** Pre-selected order ID */
  orderId?: number;
  /** Pre-selected product ID */
  productId?: number;
}

export default function NewTicketForm({
  defaultEmail = '',
  defaultName = '',
  orderId,
  productId}: NewTicketFormProps) {
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    formState: { errors }} = useForm<CreateTicketInput>({
    resolver: zodResolver(CreateTicketSchema),
    defaultValues: {
      customerEmail: defaultEmail,
      customerName: defaultName,
      category: TicketCategory.OTHER,
      priority: TicketPriority.MEDIUM,
      orderId,
      productId}});

  const onSubmit = async (data: CreateTicketInput) => {
    setIsSubmitting(true);
    setSubmitError(null);

    try {
      const response = await fetch('/api/support/tickets', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)});

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to create ticket');
      }

      // Redirect to the new ticket
      router.push(`/support/tickets/${result.data.id}?created=true`);
    } catch (error) {
      clientLogger.error('Failed to create ticket', error instanceof Error ? error : new Error(String(error)), {
        category: data.category,
        priority: data.priority
      });
      setSubmitError(
        error instanceof Error ? error.message : 'Failed to create ticket'
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      {/* Error Message */}
      {submitError && (
        <div className="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 px-4 py-3 rounded-lg">
          {submitError}
        </div>
      )}

      {/* Contact Information */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label htmlFor="customerName" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Your Name *
          </label>
          <input
            {...register('customerName')}
            type="text"
            id="customerName"
            className={`
              w-full px-4 py-2 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
              focus:outline-none focus:ring-2 focus:ring-blue-500
              placeholder:text-gray-400 dark:placeholder:text-gray-500
              ${errors.customerName ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'}
            `}
            placeholder="John Doe"
          />
          {errors.customerName && (
            <p className="mt-1 text-sm text-red-500">{errors.customerName.message}</p>
          )}
        </div>

        <div>
          <label htmlFor="customerEmail" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Email Address *
          </label>
          <input
            {...register('customerEmail')}
            type="email"
            id="customerEmail"
            className={`
              w-full px-4 py-2 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
              focus:outline-none focus:ring-2 focus:ring-blue-500
              placeholder:text-gray-400 dark:placeholder:text-gray-500
              ${errors.customerEmail ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'}
            `}
            placeholder="john@example.com"
          />
          {errors.customerEmail && (
            <p className="mt-1 text-sm text-red-500">{errors.customerEmail.message}</p>
          )}
        </div>
      </div>

      {/* Category & Priority */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label htmlFor="category" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Category *
          </label>
          <select
            {...register('category')}
            id="category"
            className={`
              w-full px-4 py-2 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
              focus:outline-none focus:ring-2 focus:ring-blue-500
              ${errors.category ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'}
            `}
          >
            {Object.entries(TICKET_CATEGORY_CONFIG).map(([value, config]) => (
              <option key={value} value={value}>
                {config.label}
              </option>
            ))}
          </select>
          {errors.category && (
            <p className="mt-1 text-sm text-red-500">{errors.category.message}</p>
          )}
        </div>

        <div>
          <label htmlFor="priority" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
            Priority
          </label>
          <select
            {...register('priority')}
            id="priority"
            className="
              w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
              focus:outline-none focus:ring-2 focus:ring-blue-500
            "
          >
            {Object.entries(TICKET_PRIORITY_CONFIG).map(([value, config]) => (
              <option key={value} value={value}>
                {config.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Subject */}
      <div>
        <label htmlFor="subject" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
          Subject *
        </label>
        <input
          {...register('subject')}
          type="text"
          id="subject"
          className={`
            w-full px-4 py-2 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
            focus:outline-none focus:ring-2 focus:ring-blue-500
            placeholder:text-gray-400 dark:placeholder:text-gray-500
            ${errors.subject ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'}
          `}
          placeholder="Brief description of your issue"
        />
        {errors.subject && (
          <p className="mt-1 text-sm text-red-500">{errors.subject.message}</p>
        )}
      </div>

      {/* Description */}
      <div>
        <label htmlFor="description" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
          Description *
        </label>
        <textarea
          {...register('description')}
          id="description"
          rows={6}
          className={`
            w-full px-4 py-2 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100
            focus:outline-none focus:ring-2 focus:ring-blue-500
            resize-none
            placeholder:text-gray-400 dark:placeholder:text-gray-500
            ${errors.description ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'}
          `}
          placeholder="Please describe your issue in detail. Include any relevant order numbers, product names, or error messages."
        />
        {errors.description && (
          <p className="mt-1 text-sm text-red-500">{errors.description.message}</p>
        )}
        <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">Minimum 20 characters</p>
      </div>

      {/* Hidden fields for order/product */}
      {orderId && <input type="hidden" {...register('orderId')} value={orderId} />}
      {productId && <input type="hidden" {...register('productId')} value={productId} />}

      {/* Submit Button */}
      <div className="flex items-center justify-end gap-4">
        <button
          type="button"
          onClick={() => router.back()}
          className="
            px-6 py-2 text-gray-700 dark:text-gray-300
            border border-gray-300 dark:border-gray-600 rounded-lg
            hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors
          "
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={isSubmitting}
          className="
            px-6 py-2 bg-blue-600 text-white
            rounded-lg font-medium
            hover:bg-blue-700 transition-colors
            disabled:bg-blue-400 disabled:cursor-not-allowed
            flex items-center gap-2
          "
        >
          {isSubmitting ? (
            <>
              <Icon name="spinner" size={16} className="animate-spin" />
              Submitting...
            </>
          ) : (
            'Submit Ticket'
          )}
        </button>
      </div>
    </form>
  );
}