// Frontend: QuestionnairePage.tsx
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import AppLayout from '@/layouts/app-layout';
import { PencilIcon, TrashIcon } from '@heroicons/react/20/solid';
import { Head, router } from '@inertiajs/react';
import { useState } from 'react';

interface Questionnaire {
    id: number;
    question_text: string;
    is_active: boolean;
}

export default function QuestionnairePage({ questionnaires: initialData }: { questionnaires: Questionnaire[] }) {
    const [questionnaires, setQuestionnaires] = useState<Questionnaire[]>(initialData);
    const [editing, setEditing] = useState<Questionnaire | null>(null);
    const [newQuestion, setNewQuestion] = useState('');
    const [isActive, setIsActive] = useState(true);
    const [isOpen, setIsOpen] = useState(false); // State untuk modal visibility

    const handleSave = () => {
        if (editing) {
            // Update existing
            router.put(
                `/questionnaires/${editing.id}`,
                { question_text: newQuestion, is_active: isActive },
                {
                    onSuccess: (page) => {
                        // Ambil data terbaru dari page.props
                        setQuestionnaires(page.props.questionnaires);
                        resetForm();
                        setIsOpen(false); // Menutup modal setelah sukses
                    },
                },
            );
        } else {
            // Create new
            router.post(
                '/questionnaires',
                { question_text: newQuestion, is_active: isActive },
                {
                    onSuccess: (page: any) => {
                        // Ambil data terbaru dari page.props
                        setQuestionnaires(page.props.questionnaires);
                        resetForm();
                        setIsOpen(false); // Menutup modal setelah sukses
                    },
                },
            );
        }
    };

    const handleDelete = (id: number) => {
        if (confirm('Yakin ingin menghapus kuisioner ini?')) {
            router.delete(`/questionnaires/${id}`, {
                onSuccess: (page) => {
                    // Update state setelah penghapusan
                    setQuestionnaires(page.props.questionnaires);
                },
            });
        }
    };

    const startEdit = (q: Questionnaire) => {
        setEditing(q);
        setNewQuestion(q.question_text);
        setIsActive(q.is_active);
        setIsOpen(true); // Membuka modal saat edit
    };

    const resetForm = () => {
        setEditing(null);
        setNewQuestion('');
        setIsActive(true);
    };

    return (
        <AppLayout breadcrumbs={[{ title: 'Kuisioner', href: '/questionnaires' }]}>
            <Head title="Daftar Kuisioner" />

            <div className="flex items-center justify-between p-4">
                <h1 className="text-2xl font-bold">Daftar Kuisioner</h1>
                <Dialog open={isOpen} onOpenChange={setIsOpen}>
                    <DialogTrigger asChild>
                        <Button onClick={() => setIsOpen(true)}>+ Tambah Kuisioner</Button>
                    </DialogTrigger>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>{editing ? 'Edit Kuisioner' : 'Tambah Kuisioner'}</DialogTitle>
                        </DialogHeader>
                        <div className="space-y-4">
                            <Textarea
                                placeholder="Tulis pertanyaan kuisioner di sini..."
                                value={newQuestion}
                                onChange={(e) => setNewQuestion(e.target.value)}
                            />
                            <label className="flex items-center gap-2">
                                <input type="checkbox" checked={isActive} onChange={(e) => setIsActive(e.target.checked)} />
                                Aktif
                            </label>
                            <div className="flex justify-end gap-2">
                                <Button variant="secondary" onClick={() => setIsOpen(false)}>
                                    Batal
                                </Button>
                                <Button onClick={handleSave}>{editing ? 'Update' : 'Simpan'}</Button>
                            </div>
                        </div>
                    </DialogContent>
                </Dialog>
            </div>

            <div className="p-4">
                <table className="mt-6 min-w-full table-auto border-collapse overflow-hidden rounded-lg bg-white shadow-md">
                    <thead className="bg-blue-600 text-white">
                        <tr>
                            <th className="px-6 py-3 text-left text-sm font-semibold">Pertanyaan</th>
                            <th className="px-6 py-3 text-left text-sm font-semibold">Status</th>
                            <th className="px-6 py-3 text-left text-sm font-semibold">Aksi</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                        {questionnaires.length > 0 ? (
                            questionnaires.map((q) => (
                                <tr key={q.id} className="transition-colors duration-200 ease-in-out hover:bg-gray-50">
                                    <td className="px-6 py-4 text-sm font-medium text-gray-700">{q.question_text}</td>
                                    <td className="px-6 py-4 text-center text-sm">
                                        <span
                                            className={`inline-block rounded-full px-2 py-1 ${
                                                q.is_active ? 'bg-green-500' : 'bg-red-500'
                                            } text-white`}
                                        >
                                            {q.is_active ? 'Aktif' : 'Nonaktif'}
                                        </span>
                                    </td>
                                    <td className="flex justify-center space-x-2 px-6 py-4 text-center text-sm">
                                        <Button
                                            size="sm"
                                            onClick={() => startEdit(q)}
                                            variant="outline"
                                            className="p-2 text-blue-600 hover:bg-blue-100"
                                        >
                                            <PencilIcon className="h-5 w-5" />
                                        </Button>
                                        <Button
                                            size="sm"
                                            onClick={() => handleDelete(q.id)}
                                            variant="destructive"
                                            className="text-dark-600 bg-red-500 p-2"
                                        >
                                            <TrashIcon className="h-5 w-5" />
                                        </Button>
                                    </td>
                                </tr>
                            ))
                        ) : (
                            <tr>
                                <td colSpan={3} className="py-4 text-center text-gray-500">
                                    Tidak ada kuisioner yang tersedia
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
        </AppLayout>
    );
}
