import { useState, useEffect } from 'react';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import FormModal from '@/Components/FormModal';
import ConfirmDeleteModal from '@/Components/ConfirmDeleteModal';
import { Head, useForm, router } from '@inertiajs/react';

export default function Index({ staff }) {
    const [showAddModal, setShowAddModal] = useState(false);
    const [editingStaff, setEditingStaff] = useState(null);
    const [deleteId, setDeleteId] = useState(null);
    const [deleting, setDeleting] = useState(false);

    const addForm = useForm({
        name: '',
        email: '',
        password: '',
        password_confirmation: '',
    });

    const editForm = useForm({
        name: '',
        email: '',
        password: '',
        password_confirmation: '',
    });

    useEffect(() => {
        if (editingStaff) {
            editForm.setData({
                name: editingStaff.name || '',
                email: editingStaff.email || '',
                password: '',
                password_confirmation: '',
            });
        }
    }, [editingStaff]);

    const openAddModal = () => {
        addForm.reset();
        addForm.clearErrors();
        setShowAddModal(true);
    };

    const handleAdd = (e) => {
        e.preventDefault();
        addForm.post(route('staff.store'), {
            onSuccess: () => { setShowAddModal(false); addForm.reset(); },
        });
    };

    const handleEdit = (e) => {
        e.preventDefault();
        editForm.put(route('staff.update', editingStaff.id), {
            onSuccess: () => { setEditingStaff(null); editForm.reset(); },
        });
    };

    const handleDelete = () => {
        setDeleting(true);
        router.delete(route('staff.destroy', deleteId), {
            onFinish: () => { setDeleting(false); setDeleteId(null); },
        });
    };

    const renderFormFields = (form, isEdit = false) => (
        <div className="space-y-4">
            <div>
                <label className="block text-sm font-medium text-gray-700">Full Name <span className="text-red-500">*</span></label>
                <input
                    type="text"
                    value={form.data.name}
                    onChange={(e) => form.setData('name', e.target.value)}
                    className="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                    placeholder="Enter staff name"
                />
                {form.errors.name && <p className="mt-1 text-sm text-red-600">{form.errors.name}</p>}
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700">Email <span className="text-red-500">*</span></label>
                <input
                    type="email"
                    value={form.data.email}
                    onChange={(e) => form.setData('email', e.target.value)}
                    className="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                    placeholder="staff@example.com"
                />
                {form.errors.email && <p className="mt-1 text-sm text-red-600">{form.errors.email}</p>}
            </div>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div>
                    <label className="block text-sm font-medium text-gray-700">
                        Password {!isEdit && <span className="text-red-500">*</span>}
                    </label>
                    <input
                        type="password"
                        value={form.data.password}
                        onChange={(e) => form.setData('password', e.target.value)}
                        className="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                        placeholder={isEdit ? 'Leave blank to keep current' : 'Enter password'}
                    />
                    {form.errors.password && <p className="mt-1 text-sm text-red-600">{form.errors.password}</p>}
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700">
                        Confirm Password {!isEdit && <span className="text-red-500">*</span>}
                    </label>
                    <input
                        type="password"
                        value={form.data.password_confirmation}
                        onChange={(e) => form.setData('password_confirmation', e.target.value)}
                        className="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                        placeholder="Confirm password"
                    />
                </div>
            </div>

            {/* Permissions Info */}
            <div className="rounded-lg bg-amber-50 border border-amber-200 p-4">
                <div className="flex items-start gap-3">
                    <svg className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <div>
                        <p className="text-sm font-medium text-amber-800">Staff Permissions</p>
                        <ul className="mt-1 text-xs text-amber-700 list-disc list-inside space-y-0.5">
                            <li>Can view all data (shops, tenants, invoices, etc.)</li>
                            <li>Can create new records (invoices, payments, readings)</li>
                            <li className="text-red-600 font-medium">Cannot edit or delete any records</li>
                            <li className="text-red-600 font-medium">Cannot access Settings or Staff management</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    );

    return (
        <AuthenticatedLayout header={<h2 className="text-xl font-semibold leading-tight text-gray-800">Staff Management</h2>}>
            <Head title="Staff" />

            <div className="py-6">
                <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                    {/* Header */}
                    <div className="flex items-center justify-between mb-6">
                        <div>
                            <h3 className="text-lg font-semibold text-gray-900">Staff Members</h3>
                            <p className="text-sm text-gray-500">Staff can view and create records but cannot edit or delete</p>
                        </div>
                        <button
                            onClick={openAddModal}
                            className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-blue-700 transition-colors"
                        >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                            </svg>
                            Add Staff
                        </button>
                    </div>

                    {/* Staff Cards */}
                    {staff.length > 0 ? (
                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                            {staff.map((member) => (
                                <div key={member.id} className="bg-white rounded-xl border border-gray-200 p-5 hover:shadow-md transition-shadow">
                                    <div className="flex items-start justify-between">
                                        <div className="flex items-center gap-3">
                                            <div className="w-11 h-11 bg-gradient-to-br from-indigo-500 to-blue-600 rounded-full flex items-center justify-center flex-shrink-0">
                                                <span className="text-white font-bold text-sm">{member.name.charAt(0).toUpperCase()}</span>
                                            </div>
                                            <div>
                                                <h4 className="text-sm font-semibold text-gray-900">{member.name}</h4>
                                                <p className="text-xs text-gray-500">{member.email}</p>
                                            </div>
                                        </div>
                                        <span className="inline-flex items-center rounded-full bg-blue-50 px-2.5 py-0.5 text-xs font-medium text-blue-700">
                                            Staff
                                        </span>
                                    </div>

                                    <div className="mt-4 flex items-center justify-between">
                                        <p className="text-xs text-gray-400">Added {new Date(member.created_at).toLocaleDateString()}</p>
                                        <div className="flex gap-2">
                                            <button
                                                onClick={() => { setEditingStaff(member); }}
                                                className="inline-flex items-center gap-1 rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200 transition-colors"
                                            >
                                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                </svg>
                                                Edit
                                            </button>
                                            <button
                                                onClick={() => setDeleteId(member.id)}
                                                className="inline-flex items-center gap-1 rounded-lg bg-red-50 px-3 py-1.5 text-xs font-medium text-red-600 hover:bg-red-100 transition-colors"
                                            >
                                                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                </svg>
                                                Delete
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className="text-center py-12 bg-white rounded-xl border border-gray-200">
                            <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                            </svg>
                            <h3 className="mt-2 text-sm font-medium text-gray-900">No staff members</h3>
                            <p className="mt-1 text-sm text-gray-500">Get started by adding a new staff member.</p>
                            <button
                                onClick={openAddModal}
                                className="mt-4 inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
                            >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                                </svg>
                                Add Staff
                            </button>
                        </div>
                    )}
                </div>
            </div>

            {/* Add Modal */}
            <FormModal show={showAddModal} onClose={() => setShowAddModal(false)} title="Add Staff Member" maxWidth="lg">
                <form onSubmit={handleAdd}>
                    {renderFormFields(addForm)}
                    <div className="mt-6 flex justify-end gap-3">
                        <button type="button" onClick={() => setShowAddModal(false)} className="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                            Cancel
                        </button>
                        <button type="submit" disabled={addForm.processing} className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50">
                            {addForm.processing ? 'Adding...' : 'Add Staff'}
                        </button>
                    </div>
                </form>
            </FormModal>

            {/* Edit Modal */}
            <FormModal show={!!editingStaff} onClose={() => setEditingStaff(null)} title="Edit Staff Member" maxWidth="lg">
                <form onSubmit={handleEdit}>
                    {renderFormFields(editForm, true)}
                    <div className="mt-6 flex justify-end gap-3">
                        <button type="button" onClick={() => setEditingStaff(null)} className="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">
                            Cancel
                        </button>
                        <button type="submit" disabled={editForm.processing} className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50">
                            {editForm.processing ? 'Saving...' : 'Save Changes'}
                        </button>
                    </div>
                </form>
            </FormModal>

            {/* Delete Confirmation */}
            <ConfirmDeleteModal
                show={!!deleteId}
                onClose={() => setDeleteId(null)}
                onConfirm={handleDelete}
                processing={deleting}
                title="Delete Staff Member"
                message="Are you sure you want to delete this staff member? This action cannot be undone."
            />
        </AuthenticatedLayout>
    );
}
