'use client';

import React, { useState } from 'react';

interface Category {
  id: string;
  name: string;
  description: string;
  questionCount: number;
  createdAt: string;
}

const QuestionCategories: React.FC = () => {
  const [categories, setCategories] = useState<Category[]>([
    {
      id: '1',
      name: 'Dasar Kuliner',
      description: 'Soal-soal tentang konsep dasar memasak dan mise en place',
      questionCount: 45,
      createdAt: '2024-01-15'
    },
    {
      id: '2',
      name: 'Teknik Memasak',
      description: 'Soal-soal tentang berbagai teknik memasak dan pengolahan makanan',
      questionCount: 38,
      createdAt: '2024-01-16'
    },
    {
      id: '3',
      name: 'Food Safety & Hygiene',
      description: 'Soal-soal tentang keamanan pangan dan sanitasi dapur',
      questionCount: 32,
      createdAt: '2024-01-17'
    },
    {
      id: '4',
      name: 'Kuliner Internasional',
      description: 'Soal-soal tentang masakan internasional dan teknik khusus',
      questionCount: 28,
      createdAt: '2024-01-18'
    },
    {
      id: '5',
      name: 'Pastry & Bakery',
      description: 'Soal-soal tentang pembuatan kue, roti, dan dessert',
      questionCount: 24,
      createdAt: '2024-01-19'
    },
    {
      id: '6',
      name: 'Menu Planning & Costing',
      description: 'Soal-soal tentang perencanaan menu dan perhitungan food cost',
      questionCount: 18,
      createdAt: '2024-01-20'
    }
  ]);

  const [showAddModal, setShowAddModal] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    description: ''
  });

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleAddCategory = () => {
    setFormData({ name: '', description: '' });
    setEditingCategory(null);
    setShowAddModal(true);
  };

  const handleEditCategory = (category: Category) => {
    setFormData({
      name: category.name,
      description: category.description
    });
    setEditingCategory(category);
    setShowAddModal(true);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.name.trim()) {
      alert('Nama kategori harus diisi');
      return;
    }

    if (editingCategory) {
      // Update existing category
      setCategories(prev => prev.map(cat => 
        cat.id === editingCategory.id 
          ? { ...cat, name: formData.name, description: formData.description }
          : cat
      ));
      alert('Kategori berhasil diperbarui!');
    } else {
      // Add new category
      const newCategory: Category = {
        id: (categories.length + 1).toString(),
        name: formData.name,
        description: formData.description,
        questionCount: 0,
        createdAt: new Date().toISOString().split('T')[0]
      };
      setCategories(prev => [...prev, newCategory]);
      alert('Kategori berhasil ditambahkan!');
    }

    setShowAddModal(false);
    setFormData({ name: '', description: '' });
    setEditingCategory(null);
  };

  const handleDeleteCategory = (categoryId: string) => {
    const category = categories.find(cat => cat.id === categoryId);
    if (category && category.questionCount > 0) {
      alert(`Tidak dapat menghapus kategori "${category.name}" karena masih memiliki ${category.questionCount} soal.`);
      return;
    }

    if (confirm('Apakah Anda yakin ingin menghapus kategori ini?')) {
      setCategories(prev => prev.filter(cat => cat.id !== categoryId));
      alert('Kategori berhasil dihapus!');
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('id-ID', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold text-gray-900">Kategori Soal</h2>
          <p className="text-gray-600 mt-1">Kelola kategori untuk mengorganisir soal-soal</p>
        </div>
        <button
          onClick={handleAddCategory}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          + Tambah Kategori
        </button>
      </div>

      {/* Categories Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {categories.map((category) => (
          <div key={category.id} className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="flex items-start justify-between mb-4">
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-gray-900">{category.name}</h3>
                <p className="text-gray-600 text-sm mt-1">{category.description}</p>
              </div>
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => handleEditCategory(category)}
                  className="text-blue-600 hover:text-blue-800 text-sm"
                >
                  Edit
                </button>
                <button
                  onClick={() => handleDeleteCategory(category.id)}
                  className="text-red-600 hover:text-red-800 text-sm"
                >
                  Hapus
                </button>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-600">Jumlah Soal:</span>
                <span className="text-lg font-semibold text-blue-600">{category.questionCount}</span>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-600">Dibuat:</span>
                <span className="text-sm text-gray-900">{formatDate(category.createdAt)}</span>
              </div>
            </div>

            <div className="mt-4 pt-4 border-t border-gray-200">
              <button className="w-full text-center text-blue-600 hover:text-blue-800 text-sm font-medium">
                Lihat Semua Soal
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Add/Edit Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
            <div className="p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">
                {editingCategory ? 'Edit Kategori' : 'Tambah Kategori Baru'}
              </h3>
              
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Nama Kategori *
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    placeholder="Masukkan nama kategori"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Deskripsi
                  </label>
                  <textarea
                    name="description"
                    value={formData.description}
                    onChange={handleInputChange}
                    rows={3}
                    placeholder="Masukkan deskripsi kategori"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div className="flex justify-end space-x-3 pt-4">
                  <button
                    type="button"
                    onClick={() => setShowAddModal(false)}
                    className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
                  >
                    Batal
                  </button>
                  <button
                    type="submit"
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    {editingCategory ? 'Simpan Perubahan' : 'Tambah Kategori'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default QuestionCategories;