import { useState, useRef } from 'react';
import { useRouter } from 'next/router';
import Image from 'next/image';
import { Upload, X, Plus, Trash2 } from 'lucide-react';

interface ProductFormProps {
  product?: {
    id?: string;
    name?: string;
    description?: string;
    price?: number;
    compareAtPrice?: number;
    sku?: string;
    inventory?: number;
    categoryId?: string;
    images?: string[];
    variants?: any[];
  };
  onSubmit: (data: any) => void;
  categories?: { id: string; name: string }[];
  isSubmitting?: boolean;
}

export default function ProductForm({ 
  product, 
  onSubmit, 
  categories = [],
  isSubmitting = false 
}: ProductFormProps) {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const [formData, setFormData] = useState({
    name: product?.name || '',
    description: product?.description || '',
    price: product?.price || '',
    compareAtPrice: product?.compareAtPrice || '',
    sku: product?.sku || '',
    inventory: product?.inventory || 0,
    categoryId: product?.categoryId || '',
    images: product?.images || [],
  });
  const [uploadedImages, setUploadedImages] = useState<File[]>([]);
  const [variants, setVariants] = useState(product?.variants || []);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length + formData.images.length + uploadedImages.length > 10) {
      setErrors(prev => ({ ...prev, images: 'สูงสุด 10 รูปเท่านั้น' }));
      return;
    }
    setUploadedImages(prev => [...prev, ...files]);
    setErrors(prev => {
      const { images: _, ...rest } = prev;
      return rest;
    });
  };

  const removeImage = (index: number, isUploaded: boolean) => {
    if (isUploaded) {
      setFormData(prev => ({
        ...prev,
        images: prev.images.filter((_, i) => i !== index)
      }));
    } else {
      setUploadedImages(prev => prev.filter((_, i) => i !== index));
    }
  };

  const addVariant = () => {
    setVariants(prev => [...prev, { 
      id: `variant-${Date.now()}`,
      name: '', 
      price: '', 
      inventory: 0,
      attributes: {}
    }]);
  };

  const updateVariant = (index: number, field: string, value: any) => {
    setVariants(prev => prev.map((v, i) => 
      i === index ? { ...v, [field]: value } : v
    ));
  };

  const removeVariant = (index: number) => {
    setVariants(prev => prev.filter((_, i) => i !== index));
  };

  const validate = () => {
    const newErrors: Record<string, string> = {};
    if (!formData.name.trim()) newErrors.name = 'กรุณากรอกชื่อสินค้า';
    if (!formData.price) newErrors.price = 'กรุณากรอกราคา';
    if (formData.price && parseFloat(formData.price) <= 0) newErrors.price = 'ราคาต้องมากกว่า 0';
    if (formData.compareAtPrice && parseFloat(formData.compareAtPrice) <= parseFloat(formData.price)) {
      newErrors.compareAtPrice = 'ราคาเดิมต้องมากกว่าราคาปัจจุบัน';
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    const submitData = {
      ...formData,
      price: parseFloat(formData.price),
      compareAtPrice: formData.compareAtPrice ? parseFloat(formData.compareAtPrice) : null,
      inventory: parseInt(formData.inventory.toString()) || 0,
      variants: variants.map(v => ({
        ...v,
        price: v.price ? parseFloat(v.price) : 0
      })),
      uploadedImages
    };

    await onSubmit(submitData);
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-8">
      {/* Basic Info */}
      <div className="bg-white rounded-xl border p-6 space-y-6">
        <h3 className="font-medium">ข้อมูลพื้นฐาน</h3>
        
        <div>
          <label className="block text-sm font-medium mb-1">ชื่อสินค้า *</label>
          <input
            type="text"
            required
            value={formData.name}
            onChange={e => setFormData({ ...formData, name: e.target.value })}
            placeholder="เช่น เสื้อยืดคอกลม Cotton 100%"
            className={`w-full border rounded-lg px-3 py-2 ${errors.name ? 'border-red-500' : ''}`}
          />
          {errors.name && <p className="text-red-500 text-sm mt-1">{errors.name}</p>}
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">รายละเอียด</label>
          <textarea
            value={formData.description}
            onChange={e => setFormData({ ...formData, description: e.target.value })}
            placeholder="อธิบายรายละเอียดสินค้า เช่น วัสดุ, ขนาด, วิธีใช้งาน..."
            className="w-full border rounded-lg px-3 py-2 h-32 resize-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">หมวดหมู่</label>
          <select
            value={formData.categoryId}
            onChange={e => setFormData({ ...formData, categoryId: e.target.value })}
            className="w-full border rounded-lg px-3 py-2"
          >
            <option value="">เลือกหมวดหมู่</option>
            {categories.map(cat => (
              <option key={cat.id} value={cat.id}>{cat.name}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Pricing */}
      <div className="bg-white rounded-xl border p-6 space-y-6">
        <h3 className="font-medium">ราคาและสต็อก</h3>
        
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium mb-1">ราคา *</label>
            <div className="relative">
              <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">฿</span>
              <input
                type="number"
                required
                min="0"
                step="0.01"
                value={formData.price}
                onChange={e => setFormData({ ...formData, price: e.target.value })}
                placeholder="0.00"
                className={`w-full border rounded-lg pl-8 pr-3 py-2 ${errors.price ? 'border-red-500' : ''}`}
              />
            </div>
            {errors.price && <p className="text-red-500 text-sm mt-1">{errors.price}</p>}
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">ราคาเดิม (ถ้าลดราคา)</label>
            <div className="relative">
              <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">฿</span>
              <input
                type="number"
                min="0"
                step="0.01"
                value={formData.compareAtPrice}
                onChange={e => setFormData({ ...formData, compareAtPrice: e.target.value })}
                placeholder="0.00"
                className={`w-full border rounded-lg pl-8 pr-3 py-2 ${errors.compareAtPrice ? 'border-red-500' : ''}`}
              />
            </div>
            {errors.compareAtPrice && <p className="text-red-500 text-sm mt-1">{errors.compareAtPrice}</p>}
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium mb-1">SKU (รหัสสินค้า)</label>
            <input
              type="text"
              value={formData.sku}
              onChange={e => setFormData({ ...formData, sku: e.target.value })}
              placeholder="SKU-001"
              className="w-full border rounded-lg px-3 py-2"
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1">สต็อก *</label>
            <input
              type="number"
              required
              min="0"
              value={formData.inventory}
              onChange={e => setFormData({ ...formData, inventory: parseInt(e.target.value) || 0 })}
              className="w-full border rounded-lg px-3 py-2"
            />
          </div>
        </div>
      </div>

      {/* Images */}
      <div className="bg-white rounded-xl border p-6 space-y-6">
        <h3 className="font-medium">รูปภาพสินค้า</h3>
        
        <div className="grid grid-cols-5 gap-3">
          {formData.images.map((url, i) => (
            <div key={`existing-${i}`} className="relative aspect-square rounded-lg overflow-hidden bg-gray-100 group">
              <img src={url} alt="" className="w-full h-full object-cover" />
              <button
                type="button"
                onClick={() => removeImage(i, true)}
                className="absolute top-1 right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <X className="w-4 h-4" />
              </button>
              {i === 0 && (
                <span className="absolute bottom-1 left-1 bg-blue-500 text-white text-xs px-1 rounded">
                  หลัก
                </span>
              )}
            </div>
          ))}
          {uploadedImages.map((file, i) => (
            <div key={`new-${i}`} className="relative aspect-square rounded-lg overflow-hidden bg-gray-100 group">
              <img 
                src={URL.createObjectURL(file)} 
                alt="" 
                className="w-full h-full object-cover" 
              />
              <button
                type="button"
                onClick={() => removeImage(i, false)}
                className="absolute top-1 right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          ))}
          {(formData.images.length + uploadedImages.length) < 10 && (
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              className="aspect-square border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center text-gray-400 hover:border-blue-400 hover:text-blue-500 transition-colors"
            >
              <Plus className="w-8 h-8" />
              <span className="text-xs mt-1">เพิ่มรูป</span>
            </button>
          )}
        </div>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          multiple
          onChange={handleImageUpload}
          className="hidden"
        />
        <p className="text-xs text-gray-500">
          รูปแรกจะเป็นรูปหลัก สูงสุด 10 รูป ขนาดแนะนำ 800x800px
        </p>
        {errors.images && <p className="text-red-500 text-sm">{errors.images}</p>}
      </div>

      {/* Variants */}
      <div className="bg-white rounded-xl border p-6 space-y-6">
        <div className="flex items-center justify-between">
          <h3 className="font-medium">ตัวเลือกสินค้า</h3>
          <button
            type="button"
            onClick={addVariant}
            className="text-sm text-blue-600 hover:text-blue-700 flex items-center gap-1"
          >
            <Plus className="w-4 h-4" />
            เพิ่มตัวเลือก
          </button>
        </div>

        {variants.length > 0 ? (
          <div className="space-y-4">
            {variants.map((variant, index) => (
              <div key={variant.id} className="grid grid-cols-4 gap-3 p-4 bg-gray-50 rounded-lg">
                <input
                  type="text"
                  value={variant.name}
                  onChange={e => updateVariant(index, 'name', e.target.value)}
                  placeholder="ชื่อตัวเลือก (เช่น S, M, L)"
                  className="border rounded-lg px-3 py-2"
                />
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm">฿</span>
                  <input
                    type="number"
                    value={variant.price}
                    onChange={e => updateVariant(index, 'price', e.target.value)}
                    placeholder="ราคา"
                    className="w-full border rounded-lg pl-7 pr-3 py-2"
                  />
                </div>
                <input
                  type="number"
                  value={variant.inventory}
                  onChange={e => updateVariant(index, 'inventory', parseInt(e.target.value) || 0)}
                  placeholder="สต็อก"
                  className="border rounded-lg px-3 py-2"
                />
                <button
                  type="button"
                  onClick={() => removeVariant(index)}
                  className="text-red-500 hover:text-red-700 flex items-center justify-center"
                >
                  <Trash2 className="w-5 h-5" />
                </button>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-gray-500 text-center py-4">
            ไม่มีตัวเลือกสินค้า
          </p>
        )}
      </div>

      {/* Submit */}
      <button
        type="submit"
        disabled={isSubmitting}
        className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium transition-colors"
      >
        {isSubmitting ? 'กำลังบันทึก...' : product?.id ? 'บันทึกการเปลี่ยนแปลง' : 'สร้างสินค้า'}
      </button>
    </form>
  );
}
