import { useState, FormEvent } from 'react';
import Swal from 'sweetalert2';
import { Plus, Edit, Trash2, HelpCircle, Layers } from 'lucide-react';
import { Aspect, Question } from '../../types';

interface QuestionnaireManagementProps {
  aspects: Aspect[];
  questions: Question[];
  onAddAspect: (aspect: Omit<Aspect, 'id'>) => void;
  onEditAspect: (id: number, aspect: Omit<Aspect, 'id'>) => void;
  onDeleteAspect: (id: number) => void;
  onAddQuestion: (q: Omit<Question, 'id'>) => void;
  onEditQuestion: (id: number, q: Omit<Question, 'id'>) => void;
  onDeleteQuestion: (id: number) => void;
}

export default function QuestionnaireManagement({
  aspects,
  questions,
  onAddAspect,
  onEditAspect,
  onDeleteAspect,
  onAddQuestion,
  onEditQuestion,
  onDeleteQuestion
}: QuestionnaireManagementProps) {
  const [subTab, setSubTab] = useState<'aspects' | 'questions'>('aspects');

  // Aspect Form State
  const [editingAspectId, setEditingAspectId] = useState<number | null>(null);
  const [aspectTitle, setAspectTitle] = useState('');
  const [aspectDesc, setAspectDesc] = useState('');

  // Question Form State
  const [editingQuestionId, setEditingQuestionId] = useState<number | null>(null);
  const [questionText, setQuestionText] = useState('');
  const [questionAspectId, setQuestionAspectId] = useState<number | ''>('');
  const [filterAspectId, setFilterAspectId] = useState<number | ''>('');

  const handleAspectSubmit = (e: FormEvent) => {
    e.preventDefault();
    if (!aspectTitle.trim() || !aspectDesc.trim()) return;

    if (editingAspectId !== null) {
      onEditAspect(editingAspectId, { title: aspectTitle.trim(), description: aspectDesc.trim() });
      Swal.fire({
        icon: 'success',
        title: 'Berhasil!',
        text: 'Aspek kuesioner berhasil diperbarui.',
        timer: 1500,
        showConfirmButton: false
      });
    } else {
      onAddAspect({ title: aspectTitle.trim(), description: aspectDesc.trim() });
      Swal.fire({
        icon: 'success',
        title: 'Berhasil!',
        text: 'Aspek kuesioner baru berhasil ditambahkan.',
        timer: 1500,
        showConfirmButton: false
      });
    }
    setEditingAspectId(null);
    setAspectTitle('');
    setAspectDesc('');
  };

  const handleQuestionSubmit = (e: FormEvent) => {
    e.preventDefault();
    if (!questionText.trim() || !questionAspectId) return;

    if (editingQuestionId !== null) {
      onEditQuestion(editingQuestionId, { aspectId: Number(questionAspectId), text: questionText.trim() });
      Swal.fire({
        icon: 'success',
        title: 'Berhasil!',
        text: 'Pertanyaan kuesioner berhasil diperbarui.',
        timer: 1500,
        showConfirmButton: false
      });
    } else {
      onAddQuestion({ aspectId: Number(questionAspectId), text: questionText.trim() });
      Swal.fire({
        icon: 'success',
        title: 'Berhasil!',
        text: 'Pertanyaan kuesioner baru berhasil ditambahkan.',
        timer: 1500,
        showConfirmButton: false
      });
    }
    setEditingQuestionId(null);
    setQuestionText('');
    setQuestionAspectId('');
  };

  const handleDeleteAspectClick = (aspect: Aspect) => {
    Swal.fire({
      title: 'Hapus Aspek?',
      text: `Apakah Anda yakin ingin menghapus "${aspect.title}"? Seluruh pertanyaan di dalam aspek ini serta data nilai kuesioner yang terkait akan ikut terhapus permanen!`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Ya, Hapus Aspek!',
      cancelButtonText: 'Batal'
    }).then((result) => {
      if (result.isConfirmed) {
        onDeleteAspect(aspect.id);
        Swal.fire({
          icon: 'success',
          title: 'Terhapus!',
          text: `Aspek "${aspect.title}" berhasil dihapus.`,
          timer: 1500,
          showConfirmButton: false
        });
      }
    });
  };

  const handleDeleteQuestionClick = (q: Question) => {
    Swal.fire({
      title: 'Hapus Pertanyaan?',
      text: `Apakah Anda yakin ingin menghapus pertanyaan "${q.text}"? Tindakan ini akan menghapus detail skor terkait pertanyaan ini dari seluruh responden.`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Ya, Hapus!',
      cancelButtonText: 'Batal'
    }).then((result) => {
      if (result.isConfirmed) {
        onDeleteQuestion(q.id);
        Swal.fire({
          icon: 'success',
          title: 'Terhapus!',
          text: 'Pertanyaan berhasil dihapus.',
          timer: 1500,
          showConfirmButton: false
        });
      }
    });
  };

  const filteredQuestions = filterAspectId
    ? questions.filter(q => q.aspectId === Number(filterAspectId))
    : questions;

  return (
    <div className="space-y-6">
      {/* Sub-tab selection menu */}
      <div className="flex border-b border-slate-200 dark:border-slate-700/60 gap-4 pb-0.5">
        <button
          onClick={() => setSubTab('aspects')}
          className={`flex items-center gap-1.5 pb-2 text-xs font-bold uppercase tracking-wider border-b-2 transition cursor-pointer ${
            subTab === 'aspects'
              ? 'border-blue-600 text-blue-700 dark:text-blue-400 font-extrabold'
              : 'border-transparent text-slate-400 hover:text-slate-600 dark:text-slate-400 dark:hover:text-slate-300'
          }`}
        >
          <Layers className="h-4 w-4" />
          <span>Kelola Aspek ({aspects.length})</span>
        </button>
        <button
          onClick={() => setSubTab('questions')}
          className={`flex items-center gap-1.5 pb-2 text-xs font-bold uppercase tracking-wider border-b-2 transition cursor-pointer ${
            subTab === 'questions'
              ? 'border-blue-600 text-blue-700 dark:text-blue-400 font-extrabold'
              : 'border-transparent text-slate-400 hover:text-slate-600 dark:text-slate-400 dark:hover:text-slate-300'
          }`}
        >
          <HelpCircle className="h-4 w-4" />
          <span>Kelola Pertanyaan ({questions.length})</span>
        </button>
      </div>

      {subTab === 'aspects' ? (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
          {/* Left panel: Aspect list */}
          <div className="bg-white dark:bg-slate-800 p-6 rounded-2xl border border-slate-100 dark:border-slate-700/60 shadow-sm lg:col-span-8">
            <h3 className="font-extrabold text-slate-800 dark:text-white text-base mb-1">Kelola Aspek Kuesioner</h3>
            <p className="text-xs text-slate-400 mb-6">Aspek kuesioner utama yang membagi butir pertanyaan.</p>
            <div className="space-y-4">
              {aspects.length === 0 ? (
                <p className="text-xs text-slate-400 italic text-center py-4">Belum ada aspek terdaftar.</p>
              ) : (
                aspects.map((aspect) => (
                  <div key={aspect.id} className="p-4 bg-slate-50 dark:bg-slate-900 border border-slate-100 dark:border-slate-800 rounded-xl flex justify-between items-start gap-4">
                    <div className="space-y-1">
                      <span className="text-[10px] font-mono font-bold text-blue-600 bg-blue-50 dark:bg-blue-950/40 px-2 py-0.5 rounded">
                        Aspek ID: {aspect.id}
                      </span>
                      <h4 className="font-bold text-sm text-slate-800 dark:text-white pt-1">{aspect.title}</h4>
                      <p className="text-xs text-slate-500 dark:text-slate-400 leading-relaxed">{aspect.description}</p>
                    </div>
                    <div className="flex gap-1 shrink-0 mt-1">
                      <button
                        onClick={() => {
                          setEditingAspectId(aspect.id);
                          setAspectTitle(aspect.title);
                          setAspectDesc(aspect.description);
                        }}
                        className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-slate-800 rounded-lg transition cursor-pointer"
                        title="Edit Aspek"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleDeleteAspectClick(aspect)}
                        className="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/20 rounded-lg transition cursor-pointer"
                        title="Hapus Aspek"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Right panel: Aspect form */}
          <div className="bg-white dark:bg-slate-800 p-6 rounded-2xl border border-slate-100 dark:border-slate-700/60 shadow-sm lg:col-span-4 h-fit space-y-4">
            <h3 className="font-extrabold text-slate-800 dark:text-white text-base">
              {editingAspectId !== null ? 'Modifikasi Aspek' : 'Tambah Aspek Baru'}
            </h3>
            <form onSubmit={handleAspectSubmit} className="space-y-4">
              <div>
                <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1.5">Judul Aspek</label>
                <input
                  type="text"
                  required
                  value={aspectTitle}
                  onChange={(e) => setAspectTitle(e.target.value)}
                  placeholder="Contoh: Aspek Kepemimpinan Visioner"
                  className="w-full text-xs px-3.5 py-2 border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-800 dark:text-white rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1.5">Deskripsi Singkat</label>
                <textarea
                  required
                  rows={4}
                  value={aspectDesc}
                  onChange={(e) => setAspectDesc(e.target.value)}
                  placeholder="Deskripsikan aspek penilaian ini secara informatif..."
                  className="w-full text-xs px-3.5 py-2 border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-800 dark:text-white rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none font-sans"
                />
              </div>
              <div className="flex gap-2">
                {editingAspectId !== null && (
                  <button
                    type="button"
                    onClick={() => {
                      setEditingAspectId(null);
                      setAspectTitle('');
                      setAspectDesc('');
                    }}
                    className="flex-1 py-2 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-650 text-slate-700 dark:text-slate-200 rounded-xl text-xs font-bold transition cursor-pointer"
                  >
                    Batal
                  </button>
                )}
                <button
                  type="submit"
                  className="flex-2 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-xs font-bold transition shadow-md cursor-pointer flex items-center justify-center gap-1.5"
                >
                  <Plus className="h-4 w-4" />
                  <span>{editingAspectId !== null ? 'Simpan' : 'Daftarkan Aspek'}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
          {/* Left panel: Question list */}
          <div className="bg-white dark:bg-slate-800 p-6 rounded-2xl border border-slate-100 dark:border-slate-700/60 shadow-sm lg:col-span-8">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
              <div>
                <h3 className="font-extrabold text-slate-800 dark:text-white text-base">Kelola Pertanyaan Kuesioner</h3>
                <p className="text-xs text-slate-400 mt-0.5">Butir-butir pernyataan kuesioner evaluasi.</p>
              </div>
              {/* Filter aspects */}
              <select
                value={filterAspectId}
                onChange={(e) => setFilterAspectId(e.target.value === '' ? '' : Number(e.target.value))}
                className="text-xs px-3 py-2 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-800 dark:text-white focus:outline-none focus:ring-1 focus:ring-blue-500 w-full sm:w-56 cursor-pointer"
              >
                <option value="">Semua Aspek ({aspects.length})</option>
                {aspects.map(a => (
                  <option key={a.id} value={a.id}>{a.title}</option>
                ))}
              </select>
            </div>

            <div className="space-y-3.5">
              {filteredQuestions.length === 0 ? (
                <p className="text-xs text-slate-400 italic text-center py-4">Belum ada pertanyaan terdaftar.</p>
              ) : (
                filteredQuestions.map((q) => {
                  const currentAspect = aspects.find(a => a.id === q.aspectId) || { title: 'Aspek Terhapus' };
                  return (
                    <div key={q.id} className="p-4 bg-slate-50 dark:bg-slate-900 border border-slate-100 dark:border-slate-800 rounded-xl flex justify-between items-center gap-4">
                      <div className="space-y-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="text-[9px] font-bold text-emerald-600 bg-emerald-50 dark:bg-emerald-950/30 px-2 py-0.5 rounded">
                            {currentAspect.title}
                          </span>
                          <span className="text-[9px] font-mono font-bold text-slate-400 bg-white dark:bg-slate-800 border dark:border-slate-700 px-1.5 py-0.5 rounded">
                            ID: {q.id}
                          </span>
                        </div>
                        <p className="font-bold text-xs sm:text-sm text-slate-800 dark:text-white leading-relaxed pt-1.5">{q.text}</p>
                      </div>
                      <div className="flex gap-1 shrink-0">
                        <button
                          onClick={() => {
                            setEditingQuestionId(q.id);
                            setQuestionText(q.text);
                            setQuestionAspectId(q.aspectId);
                          }}
                          className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-slate-800 rounded-lg transition cursor-pointer"
                          title="Edit Pertanyaan"
                        >
                          <Edit className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => handleDeleteQuestionClick(q)}
                          className="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/20 rounded-lg transition cursor-pointer"
                          title="Hapus Pertanyaan"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </div>
                  );
                })
              )}
            </div>
          </div>

          {/* Right panel: Question form */}
          <div className="bg-white dark:bg-slate-800 p-6 rounded-2xl border border-slate-100 dark:border-slate-700/60 shadow-sm lg:col-span-4 h-fit space-y-4">
            <h3 className="font-extrabold text-slate-800 dark:text-white text-base">
              {editingQuestionId !== null ? 'Modifikasi Pertanyaan' : 'Tambah Pertanyaan'}
            </h3>
            <form onSubmit={handleQuestionSubmit} className="space-y-4">
              <div>
                <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1.5">Pilih Aspek Penilaian</label>
                <select
                  required
                  value={questionAspectId}
                  onChange={(e) => setQuestionAspectId(e.target.value === '' ? '' : Number(e.target.value))}
                  className="w-full text-xs px-3 py-2 border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-800 dark:text-white rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 cursor-pointer"
                >
                  <option value="">-- Pilih Aspek --</option>
                  {aspects.map((a) => (
                    <option key={a.id} value={a.id}>{a.title}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-widest mb-1.5">Teks Pertanyaan / Pernyataan</label>
                <textarea
                  required
                  rows={4}
                  value={questionText}
                  onChange={(e) => setQuestionText(e.target.value)}
                  placeholder="Contoh: Pimpinan senantiasa bersikap adil dalam penugasan kerja..."
                  className="w-full text-xs px-3.5 py-2 border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-800 dark:text-white rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none font-sans"
                />
              </div>
              <div className="flex gap-2">
                {editingQuestionId !== null && (
                  <button
                    type="button"
                    onClick={() => {
                      setEditingQuestionId(null);
                      setQuestionText('');
                      setQuestionAspectId('');
                    }}
                    className="flex-1 py-2 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-650 text-slate-700 dark:text-slate-200 rounded-xl text-xs font-bold transition cursor-pointer"
                  >
                    Batal
                  </button>
                )}
                <button
                  type="submit"
                  className="flex-2 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-xs font-bold transition shadow-md cursor-pointer flex items-center justify-center gap-1.5"
                >
                  <Plus className="h-4 w-4" />
                  <span>{editingQuestionId !== null ? 'Simpan' : 'Daftarkan Pertanyaan'}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
