'use client';
import React, { useEffect, useRef, useState } from 'react';
import ImageUploader from './ImageUploader';

type ProductForm = {
  name: string;
  shortDescription: string;
  description: string;
  price: number | '';
  salePrice: number | '';
  downloadLimit: number;
  downloadExpiryDays: number;
  categories: number[];
  tags: string[];
};

type CategoryOption = {
  id: number;
  name: string;
};

export default function ServiceForm() {
  const [form, setForm] = useState<ProductForm>({
    name: '',
    shortDescription: '',
    description: '',
    price: '',
    salePrice: '',
    downloadLimit: 1,
    downloadExpiryDays: 30,
    categories: [],
    tags: [],
  });
  const [categories, setCategories] = useState<CategoryOption[]>([]);
  const [loading, setLoading] = useState(false);
  const mediaIdsRef = useRef<number[]>([]);

  useEffect(() => {
    async function loadCategories() {
      try {
        const response = await fetch('/api/wp/categories');
        if (!response.ok) return;
        const data = await response.json();
        setCategories(data.map((category: any) => ({ id: category.id, name: category.name })));
      } catch (error) {
        console.error('Error cargando categorías', error);
      }
    }

    loadCategories();
  }, []);

  const handleInput = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = event.target;
    setForm((current) => ({
      ...current,
      [name]: name === 'price' || name === 'salePrice' ? (value === '' ? '' : Number(value)) : value,
    }));
  };

  const handleNumericChange = (field: 'downloadLimit' | 'downloadExpiryDays') => (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = Number(event.target.value);
    setForm((current) => ({ ...current, [field]: value }));
  };

  const handleTags = (event: React.ChangeEvent<HTMLInputElement>) => {
    setForm((current) => ({
      ...current,
      tags: event.target.value.split(',').map((tag) => tag.trim()).filter(Boolean),
    }));
  };

  const toggleCategory = (categoryId: number) => {
    setForm((current) => ({
      ...current,
      categories: current.categories.includes(categoryId)
        ? current.categories.filter((id) => id !== categoryId)
        : [...current.categories, categoryId],
    }));
  };

  const setMediaIds = (ids: number[]) => {
    mediaIdsRef.current = ids;
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLoading(true);

    try {
      const payload = {
        name: form.name,
        type: 'simple',
        regular_price: form.price ? String(form.price) : undefined,
        sale_price: form.salePrice ? String(form.salePrice) : undefined,
        short_description: form.shortDescription,
        description: form.description,
        virtual: true,
        downloadable: true,
        downloads: [
          {
            name: 'Cupón de Canje - Entrecupones',
            file: 'https://entrecupones.com/wp-content/uploads/cupon-comodin.pdf',
          },
        ],
        download_limit: form.downloadLimit,
        download_expiry_days: form.downloadExpiryDays,
        categories: form.categories.map((id) => ({ id })),
        tags: form.tags.map((name) => ({ name })),
        images: mediaIdsRef.current.map((id) => ({ id })),
      };

      const response = await fetch('/api/wp/products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || 'No fue posible crear el servicio.');
      }

      const result = await response.json();
      alert(`Servicio creado con éxito (ID ${result.id}).`);
      setForm({
        name: '',
        shortDescription: '',
        description: '',
        price: '',
        salePrice: '',
        downloadLimit: 1,
        downloadExpiryDays: 30,
        categories: [],
        tags: [],
      });
      mediaIdsRef.current = [];
    } catch (error: any) {
      alert(error.message || 'Error creando el servicio.');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="grid gap-6">
        <div>
          <label htmlFor="name" className="block text-sm font-medium text-slate-700">Nombre del producto</label>
          <input
            id="name"
            name="name"
            value={form.name}
            onChange={handleInput}
            className="mt-2 w-full rounded-3xl border border-slate-300 bg-white px-4 py-3 text-sm shadow-sm focus:border-blue-500 focus:outline-none"
            required
          />
        </div>

        <div>
          <label htmlFor="shortDescription" className="block text-sm font-medium text-slate-700">Descripción corta</label>
          <input
            id="shortDescription"
            name="shortDescription"
            value={form.shortDescription}
            onChange={handleInput}
            className="mt-2 w-full rounded-3xl border border-slate-300 bg-white px-4 py-3 text-sm shadow-sm focus:border-blue-500 focus:outline-none"
          />
        </div>

        <div>
          <label htmlFor="description" className="block text-sm font-medium text-slate-700">Descripción detallada</label>
          <textarea
            id="description"
            name="description"
            value={form.description}
            onChange={handleInput}
            rows={6}
            className="mt-2 w-full rounded-3xl border border-slate-300 bg-white px-4 py-3 text-sm shadow-sm focus:border-blue-500 focus:outline-none"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
        <div>
          <label htmlFor="price" className="block text-sm font-medium text-slate-700">Precio normal (Bs.)</label>
          <input
            id="price"
            name="price"
            type="number"
            step="0.01"
            value={form.price}
            onChange={handleInput}
            className="mt-2 w-full rounded-3xl border border-slate-300 bg-white px-4 py-3 text-sm shadow-sm focus:border-blue-500 focus:outline-none"
          />
        </div>

        <div>
          <label htmlFor="salePrice" className="block text-sm font-medium text-slate-700">Precio rebajado (Bs.)</label>
          <input
            id="salePrice"
            name="salePrice"
            type="number"
            step="0.01"
            value={form.salePrice}
            onChange={handleInput}
            className="mt-2 w-full rounded-3xl border border-slate-300 bg-white px-4 py-3 text-sm shadow-sm focus:border-blue-500 focus:outline-none"
          />
        </div>

        <div>
          <label htmlFor="downloadLimit" className="block text-sm font-medium text-slate-700">Límite de descargas</label>
          <input
            id="downloadLimit"
            name="downloadLimit"
            type="number"
            min="1"
            value={form.downloadLimit}
            onChange={handleNumericChange('downloadLimit')}
            className="mt-2 w-full rounded-3xl border border-slate-300 bg-white px-4 py-3 text-sm shadow-sm focus:border-blue-500 focus:outline-none"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
        <div>
          <label htmlFor="downloadExpiryDays" className="block text-sm font-medium text-slate-700">Caducidad de descarga (días)</label>
          <input
            id="downloadExpiryDays"
            name="downloadExpiryDays"
            type="number"
            min="1"
            value={form.downloadExpiryDays}
            onChange={handleNumericChange('downloadExpiryDays')}
            className="mt-2 w-full rounded-3xl border border-slate-300 bg-white px-4 py-3 text-sm shadow-sm focus:border-blue-500 focus:outline-none"
          />
        </div>

        <div>
          <label htmlFor="tags" className="block text-sm font-medium text-slate-700">Etiquetas (separadas por comas)</label>
          <input
            id="tags"
            name="tags"
            value={form.tags.join(', ')}
            onChange={handleTags}
            className="mt-2 w-full rounded-3xl border border-slate-300 bg-white px-4 py-3 text-sm shadow-sm focus:border-blue-500 focus:outline-none"
            placeholder="spa, bienestar, fin de semana"
          />
        </div>
      </div>

      <div>
        <p className="text-sm font-semibold text-slate-800">Categorías</p>
        <div className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
          {categories.map((category) => (
            <label key={category.id} className="inline-flex items-center gap-2 rounded-3xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm">
              <input
                type="checkbox"
                checked={form.categories.includes(category.id)}
                onChange={() => toggleCategory(category.id)}
                className="h-4 w-4 rounded border-slate-300 text-blue-600"
              />
              <span>{category.name}</span>
            </label>
          ))}
        </div>
      </div>

      <div>
        <ImageUploader maxFiles={4} onUploadIds={setMediaIds} />
      </div>

      <div className="flex justify-end">
        <button
          type="submit"
          disabled={loading}
          className="inline-flex items-center justify-center rounded-3xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-70"
        >
          {loading ? 'Publicando...' : 'Crear servicio'}
        </button>
      </div>
    </form>
  );
}
