'use client';

// Ask question form. Handles the optional image upload separately so a
// failed upload does not lose the user's typed text. Image uploads
// first, then the question is created with the returned URL.

import { useRouter } from 'next/navigation';
import { FormEvent, useRef, useState } from 'react';
import { Button } from '@/components/ui/Button';

interface Props {
  categories: { id: number; name: string }[];
  defaultCategoryId?: number;
}

export function AskQuestionForm({ categories, defaultCategoryId }: Props) {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [categoryId, setCategoryId] = useState<number | ''>(defaultCategoryId ?? '');
  const [productName, setProductName] = useState('');
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function uploadImage(file: File): Promise<string | null> {
    const fd = new FormData();
    fd.append('file', file);
    const res = await fetch('/api/upload', { method: 'POST', body: fd });
    const json = await res.json();
    if (!res.ok || !json.ok) {
      setError(json.error || 'Image upload failed');
      return null;
    }
    return json.data.url as string;
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    if (!categoryId) {
      setError('Please choose a category');
      return;
    }
    setLoading(true);

    let imageUrl: string | null = null;
    if (imageFile) {
      imageUrl = await uploadImage(imageFile);
      if (!imageUrl) { setLoading(false); return; }
    }

    const res = await fetch('/api/questions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        categoryId: Number(categoryId),
        productName,
        title,
        description,
        imageUrl,
      }),
    });
    const json = await res.json();
    setLoading(false);

    if (!res.ok || !json.ok) {
      setError(json.error || 'Failed to submit question');
      return;
    }
    router.push(`/questions/${json.data.id}`);
  }

  return (
    <form onSubmit={onSubmit} className="card space-y-4 p-6">
      <div>
        <label className="label" htmlFor="category">Category</label>
        <select
          id="category"
          className="input"
          value={categoryId}
          onChange={(e) => setCategoryId(e.target.value ? Number(e.target.value) : '')}
          required
        >
          <option value="">Select a category</option>
          {categories.map((c) => (
            <option key={c.id} value={c.id}>{c.name}</option>
          ))}
        </select>
      </div>

      <div>
        <label className="label" htmlFor="product">Product Name / Model</label>
        <input
          id="product"
          className="input"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          placeholder="e.g. Drive Medical Cruiser III"
          required
        />
      </div>

      <div>
        <label className="label" htmlFor="title">Issue Title</label>
        <input
          id="title"
          className="input"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder="Short summary of the issue"
          required
          minLength={5}
          maxLength={255}
        />
      </div>

      <div>
        <label className="label" htmlFor="description">Detailed Description</label>
        <textarea
          id="description"
          className="textarea"
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="What did the customer experience? What have you already tried?"
          required
          minLength={10}
        />
      </div>

      <div>
        <label className="label" htmlFor="image">Image (optional)</label>
        <input
          id="image"
          ref={fileInputRef}
          type="file"
          accept="image/png,image/jpeg,image/webp,image/gif"
          onChange={(e) => setImageFile(e.target.files?.[0] ?? null)}
          className="block w-full text-sm text-gray-700 file:mr-3 file:rounded-md file:border-0 file:bg-brand-50 file:px-3 file:py-2 file:text-sm file:font-medium file:text-brand-700 hover:file:bg-brand-100"
        />
        {imageFile ? (
          <p className="mt-1 text-xs text-gray-500">Selected: {imageFile.name}</p>
        ) : null}
      </div>

      {error ? (
        <div className="rounded-md bg-red-50 p-3 text-sm text-red-700">{error}</div>
      ) : null}

      <div className="flex justify-end">
        <Button type="submit" disabled={loading}>
          {loading ? 'Submitting...' : 'Submit question'}
        </Button>
      </div>
    </form>
  );
}
