Spaces:
Runtime error

File size: 11,586 Bytes
6fe52ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import React, { useState } from 'react'
import { Upload, Plus, Trash2, Edit2, Download } from 'lucide-react'

export default function QuestionManager({ onQuestionsImport, currentQuestions }) {
  const [showImportModal, setShowImportModal] = useState(false)
  const [showAddModal, setShowAddModal] = useState(false)
  const [importMethod, setImportMethod] = useState('json')
  const [jsonInput, setJsonInput] = useState('')
  const [csvInput, setCsvInput] = useState('')
  const [newQuestion, setNewQuestion] = useState({
    text: '',
    options: [
      { label: 'A', text: '' },
      { label: 'B', text: '' },
      { label: 'C', text: '' },
      { label: 'D', text: '' },
      { label: 'E', text: '' }
    ],
    image: null
  })
  const [errorMessage, setErrorMessage] = useState('')
  const [successMessage, setSuccessMessage] = useState('')

  const handleJsonImport = () => {
    try {
      setErrorMessage('')
      const parsed = JSON.parse(jsonInput)

      // Validate format
      if (!Array.isArray(parsed)) {
        throw new Error('Questions must be an array')
      }

      parsed.forEach((q, idx) => {
        if (!q.text || !Array.isArray(q.options) || q.options.length !== 5) {
          throw new Error(`Question ${idx + 1}: Must have text and 5 options (A-E)`)
        }
      })

      onQuestionsImport(parsed)
      setSuccessMessage(`✅ Successfully imported ${parsed.length} questions!`)
      setJsonInput('')
      setShowImportModal(false)
      setTimeout(() => setSuccessMessage(''), 3000)
    } catch (err) {
      setErrorMessage(`❌ Error: ${err.message}`)
    }
  }

  const handleCsvImport = () => {
    try {
      setErrorMessage('')
      const lines = csvInput.trim().split('\n')
      const questions = []

      for (let i = 1; i < lines.length; i++) {
        const line = lines[i]
        if (!line.trim()) continue

        const parts = line.split('|').map(p => p.trim())
        if (parts.length < 6) {
          throw new Error(`Row ${i + 1}: Need Question|A|B|C|D|E format`)
        }

        questions.push({
          id: i,
          text: parts[0],
          options: [
            { label: 'A', text: parts[1] },
            { label: 'B', text: parts[2] },
            { label: 'C', text: parts[3] },
            { label: 'D', text: parts[4] },
            { label: 'E', text: parts[5] }
          ],
          image: parts[6] || null
        })
      }

      onQuestionsImport(questions)
      setSuccessMessage(`✅ Successfully imported ${questions.length} questions!`)
      setCsvInput('')
      setShowImportModal(false)
      setTimeout(() => setSuccessMessage(''), 3000)
    } catch (err) {
      setErrorMessage(`❌ Error: ${err.message}`)
    }
  }

  const handleAddQuestion = () => {
    try {
      setErrorMessage('')

      if (!newQuestion.text.trim()) {
        throw new Error('Question text is required')
      }

      if (newQuestion.options.some(opt => !opt.text.trim())) {
        throw new Error('All 5 options must have text')
      }

      const questionToAdd = {
        id: (currentQuestions?.length || 0) + 1,
        ...newQuestion
      }

      onQuestionsImport([...(currentQuestions || []), questionToAdd])
      setSuccessMessage('✅ Question added successfully!')

      setNewQuestion({
        text: '',
        options: [
          { label: 'A', text: '' },
          { label: 'B', text: '' },
          { label: 'C', text: '' },
          { label: 'D', text: '' },
          { label: 'E', text: '' }
        ],
        image: null
      })
      setShowAddModal(false)
      setTimeout(() => setSuccessMessage(''), 3000)
    } catch (err) {
      setErrorMessage(`❌ Error: ${err.message}`)
    }
  }

  const handleDownloadTemplate = () => {
    const template = [
      {
        id: 1,
        text: "Example question text here?",
        options: [
          { label: 'A', text: 'Option A text' },
          { label: 'B', text: 'Option B text' },
          { label: 'C', text: 'Option C text' },
          { label: 'D', text: 'Option D text' },
          { label: 'E', text: 'Option E text' }
        ],
        image: null
      }
    ]

    const element = document.createElement('a')
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(template, null, 2)))
    element.setAttribute('download', 'questions-template.json')
    element.style.display = 'none'
    document.body.appendChild(element)
    element.click()
    document.body.removeChild(element)
  }

  return (
    <div className="question-manager">
      <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <h3 className="text-lg font-bold text-blue-900 mb-3">📚 Import Your Questions</h3>

        <div className="flex gap-3 flex-wrap">
          <button
            onClick={() => setShowImportModal(true)}
            className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Upload className="w-4 h-4" />
            Import Questions
          </button>

          <button
            onClick={() => setShowAddModal(true)}
            className="flex items-center gap-2 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors"
          >
            <Plus className="w-4 h-4" />
            Add Question
          </button>

          <button
            onClick={handleDownloadTemplate}
            className="flex items-center gap-2 bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 transition-colors"
          >
            <Download className="w-4 h-4" />
            Download Template
          </button>
        </div>

        {currentQuestions?.length > 0 && (
          <p className="text-sm text-blue-700 mt-3">
            ✅ {currentQuestions.length} questions loaded
          </p>
        )}
      </div>

      {/* Success/Error Messages */}
      {successMessage && (
        <div className="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded">
          {successMessage}
        </div>
      )}
      {errorMessage && (
        <div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
          {errorMessage}
        </div>
      )}

      {/* Import Modal */}
      {showImportModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-2xl w-full mx-4 max-h-96 overflow-y-auto">
            <h3 className="text-xl font-bold mb-4">Import Questions</h3>

            <div className="mb-4">
              <label className="block text-sm font-semibold mb-2">Choose Format:</label>
              <select
                value={importMethod}
                onChange={(e) => setImportMethod(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              >
                <option value="json">JSON Format</option>
                <option value="csv">CSV Format</option>
              </select>
            </div>

            {importMethod === 'json' && (
              <div>
                <label className="block text-sm font-semibold mb-2">Paste JSON:</label>
                <textarea
                  value={jsonInput}
                  onChange={(e) => setJsonInput(e.target.value)}
                  placeholder='[{"text": "Question?", "options": [{"label": "A", "text": "..."}...], "image": null}]'
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg h-40 font-mono text-sm"
                />
              </div>
            )}

            {importMethod === 'csv' && (
              <div>
                <label className="block text-sm font-semibold mb-2">Paste CSV (Question|A|B|C|D|E|ImageURL):</label>
                <textarea
                  value={csvInput}
                  onChange={(e) => setCsvInput(e.target.value)}
                  placeholder="Question text here?|Option A|Option B|Option C|Option D|Option E|"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg h-40 font-mono text-sm"
                />
              </div>
            )}

            <div className="flex gap-3 mt-4">
              <button
                onClick={importMethod === 'json' ? handleJsonImport : handleCsvImport}
                className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700"
              >
                Import
              </button>
              <button
                onClick={() => setShowImportModal(false)}
                className="bg-gray-300 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-400"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Add Question 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 p-6 max-w-2xl w-full mx-4 max-h-96 overflow-y-auto">
            <h3 className="text-xl font-bold mb-4">Add New Question</h3>

            <div className="mb-4">
              <label className="block text-sm font-semibold mb-2">Question Text:</label>
              <textarea
                value={newQuestion.text}
                onChange={(e) => setNewQuestion({ ...newQuestion, text: e.target.value })}
                placeholder="Enter your question here..."
                className="w-full px-3 py-2 border border-gray-300 rounded-lg h-20"
              />
            </div>

            <div className="mb-4">
              <label className="block text-sm font-semibold mb-2">Options:</label>
              {newQuestion.options.map((opt, idx) => (
                <div key={idx} className="flex gap-2 mb-2">
                  <span className="w-8 font-bold">{opt.label}:</span>
                  <input
                    type="text"
                    value={opt.text}
                    onChange={(e) => {
                      const updated = [...newQuestion.options]
                      updated[idx].text = e.target.value
                      setNewQuestion({ ...newQuestion, options: updated })
                    }}
                    placeholder={`Option ${opt.label} text`}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg"
                  />
                </div>
              ))}
            </div>

            <div className="mb-4">
              <label className="block text-sm font-semibold mb-2">Image URL (optional):</label>
              <input
                type="url"
                value={newQuestion.image || ''}
                onChange={(e) => setNewQuestion({ ...newQuestion, image: e.target.value || null })}
                placeholder="https://example.com/image.jpg"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              />
            </div>

            <div className="flex gap-3">
              <button
                onClick={handleAddQuestion}
                className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700"
              >
                Add Question
              </button>
              <button
                onClick={() => setShowAddModal(false)}
                className="bg-gray-300 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-400"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}