import React, { useState } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, useForm, Link } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSave, faArrowLeft, faPlus, faBookOpen, faTrash } from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';

/**
 * Komponen untuk input Langkah Pendaftaran (Step)
 */
const StepInput = ({ index, step, onStepChange, onStepRemove, errors }) => {
    const errorPrefix = `steps.${index}`;

    return (
        <div className="flex space-x-3 mb-3 p-3 bg-gray-50 rounded-lg border border-gray-200 items-start">
            {/* Nama Langkah */}
            <div className="w-1/2">
                <input
                    type="text"
                    placeholder="Nama Langkah"
                    value={step.name || ''}
                    onChange={(e) => onStepChange(index, 'name', e.target.value)}
                    className={`w-full text-sm border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 ${errors[`${errorPrefix}.name`] ? 'border-red-500' : ''}`}
                />
                {errors[`${errorPrefix}.name`] && (
                    <div className="text-xs text-red-600 mt-1">{errors[`${errorPrefix}.name`]}</div>
                )}
            </div>

            {/* Tombol Hapus */}
            <button
                type="button"
                onClick={() => onStepRemove(index)}
                className="text-red-500 hover:text-red-700 transition flex-shrink-0 mt-2"
                title="Hapus Langkah"
            >
                <FontAwesomeIcon icon={faTrash} className="w-4 h-4" />
            </button>
        </div>
    );
};

/**
 * Komponen Utama: Create AlurPendaftaran Page
 */
export default function CreateAlurPendaftaran({ auth, errors }) {
    const { data, setData, post, processing, recentlySuccessful, reset } = useForm({
        steps: [{ name: 'Daftar Online' }],
        is_active: true,
    });

    // Fungsi untuk menambahkan langkah baru
    const addStep = () => {
        setData('steps', [...data.steps, { name: 'Langkah Baru' }]);
    };

    // Fungsi untuk menghapus langkah
    const removeStep = (index) => {
        const updatedSteps = [...data.steps];
        updatedSteps.splice(index, 1);
        setData('steps', updatedSteps);
    };

    // Fungsi untuk mengubah nilai langkah
    const handleStepChange = (index, field, value) => {
        const updatedSteps = [...data.steps];
        updatedSteps[index][field] = value;
        setData('steps', updatedSteps);
    };

    // Fungsi submit form
    const submit = (e) => {
        e.preventDefault();
        post(route('admin.kampus.alurPendaftaran.store'), {
            onSuccess: () => {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: 'Alur Pendaftaran berhasil disimpan.',
                    confirmButtonColor: '#4F46E5',
                }).then(() => {
                    reset();
                });
            },
            onError: (err) => {
                console.error('Error submitting form:', err);
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: 'Terjadi kesalahan saat menyimpan data.',
                    confirmButtonColor: '#DC2626',
                });
            },
        });
    };

    return (
        <AdminKampusLayout user={auth.user}>
            <Head title="Buat Alur Pendaftaran" />

            <div className="max-w-7xl mx-auto sm:px-6 lg:px-8 py-12">
                <form onSubmit={submit} className="bg-white overflow-hidden shadow-xl sm:rounded-lg p-8">
                    {/* Header Formulir */}
                    <div className="flex justify-between items-center mb-8 border-b pb-4">
                        <h3 className="text-2xl font-bold text-indigo-700 flex items-center">
                            <FontAwesomeIcon icon={faBookOpen} className="mr-3 w-6 h-6" />
                            Buat Alur Pendaftaran
                        </h3>
                        <div className="flex space-x-3">
                            <Link
                                href={route('admin.kampus.alurPendaftaran.index')}
                                className="inline-flex items-center px-4 py-2 bg-gray-200 border border-transparent rounded-lg font-semibold text-xs text-gray-700 uppercase tracking-widest hover:bg-gray-300 transition ease-in-out duration-150"
                            >
                                <FontAwesomeIcon icon={faArrowLeft} className="w-3 h-3 mr-2" />
                                Kembali
                            </Link>
                            <button
                                type="submit"
                                disabled={processing}
                                className={`inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-lg font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 transition ease-in-out duration-150 shadow-md ${processing ? 'opacity-75' : ''}`}
                            >
                                <FontAwesomeIcon icon={faSave} className="w-3 h-3 mr-2" />
                                {processing ? 'Menyimpan...' : 'Simpan Alur Pendaftaran'}
                            </button>
                        </div>
                    </div>

                    {/* Langkah Pendaftaran */}
                    <div className="mb-6">
                        <h4 className="text-lg font-semibold text-gray-700 mb-4">Langkah Pendaftaran</h4>
                        {data.steps.map((step, index) => (
                            <StepInput
                                key={index}
                                index={index}
                                step={step}
                                onStepChange={handleStepChange}
                                onStepRemove={removeStep}
                                errors={errors}
                            />
                        ))}
                        <button
                            type="button"
                            onClick={addStep}
                            className="inline-flex items-center px-3 py-1 bg-gray-100 border border-gray-300 rounded-lg font-medium text-xs text-gray-700 hover:bg-gray-200 transition mb-8"
                        >
                            <FontAwesomeIcon icon={faPlus} className="w-3 h-3 mr-2" />
                            Tambah Langkah
                        </button>
                    </div>

                    {/* Status Aktif */}
                    <div className="mb-8">
                        <label className="text-sm font-medium text-gray-700">
                            <input
                                type="checkbox"
                                checked={data.is_active}
                                onChange={() => setData('is_active', !data.is_active)}
                                className="mr-2"
                            />
                            Aktif
                        </label>
                    </div>

                    {/* Submit Button */}
                    <div className="flex justify-end pt-4 border-t">
                        <button
                            type="submit"
                            disabled={processing}
                            className={`inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-lg font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 transition ease-in-out duration-150 shadow-md ${processing ? 'opacity-75' : ''}`}
                        >
                            <FontAwesomeIcon icon={faSave} className="w-3 h-3 mr-2" />
                            {processing ? 'Menyimpan...' : 'Simpan Alur Pendaftaran'}
                        </button>
                    </div>
                </form>
            </div>
        </AdminKampusLayout>
    );
}
