import { useState, useEffect } from 'react';
import { X, Save, Shield, Check } from 'lucide-react';
import { rolesApi, Role } from '../../lib/rolesApi';

interface RoleModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess: () => void;
    role?: Role;
}

const RESOURCES = ['tasks', 'inventory', 'users', 'reports', 'financials'];
const PERMISSIONS = ['view', 'create', 'edit', 'delete', 'manage'];

export default function RoleModal({ isOpen, onClose, onSuccess, role }: RoleModalProps) {
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [permissions, setPermissions] = useState<any>({});
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        if (isOpen) {
            if (role) {
                setName(role.name);
                setDescription(role.description || '');
                setPermissions(role.permissions || {});
            } else {
                setName('');
                setDescription('');
                setPermissions({});
            }
        }
    }, [isOpen, role]);

    const togglePermission = (resource: string, action: string) => {
        setPermissions((prev: any) => {
            const resPerms = prev[resource] || {};
            const newValue = !resPerms[action];
            return {
                ...prev,
                [resource]: {
                    ...resPerms,
                    [action]: newValue
                }
            };
        });
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsLoading(true);
        try {
            const data = { name, description, permissions };
            if (role) {
                await rolesApi.update(role.id, data);
            } else {
                await rolesApi.create(data);
            }
            onSuccess();
            onClose();
        } catch (error) {
            console.error(error);
            alert('Failed to save role');
        } finally {
            setIsLoading(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm animate-in">
            <div className="bg-elevated w-full max-w-3xl rounded-lg shadow-xl border border-default overflow-hidden flex flex-col max-h-[90vh]">
                {/* Header */}
                <div className="px-6 py-4 border-b border-default flex justify-between items-center">
                    <h2 className="text-lg font-semibold text-primary flex items-center gap-2">
                        <Shield size={18} className="text-accent" />
                        {role ? 'Edit Role' : 'Create Role'}
                    </h2>
                    <button
                        onClick={onClose}
                        className="p-2 hover:bg-tertiary rounded-md transition-colors duration-fast"
                    >
                        <X size={18} className="text-secondary" />
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-6 space-y-6 custom-scrollbar">
                    {/* Basic Info */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-secondary mb-1.5">Role Name *</label>
                            <input
                                required
                                value={name}
                                onChange={e => setName(e.target.value)}
                                placeholder="e.g. Head Grower"
                                className="input w-full"
                            />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-secondary mb-1.5">Description</label>
                            <input
                                value={description}
                                onChange={e => setDescription(e.target.value)}
                                placeholder="Role description..."
                                className="input w-full"
                            />
                        </div>
                    </div>

                    {/* Permissions Matrix */}
                    <div>
                        <h3 className="text-sm font-medium text-primary mb-3">Permissions</h3>
                        <div className="card p-0 overflow-hidden">
                            <div className="overflow-x-auto">
                                <table className="w-full text-sm">
                                    <thead>
                                        <tr className="bg-tertiary border-b border-default">
                                            <th className="text-left py-3 px-4 font-medium text-secondary">Resource</th>
                                            {PERMISSIONS.map(p => (
                                                <th key={p} className="py-3 px-3 text-center font-medium text-secondary capitalize min-w-[70px]">
                                                    {p}
                                                </th>
                                            ))}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {RESOURCES.map((res, idx) => (
                                            <tr
                                                key={res}
                                                className={`border-b border-subtle last:border-0 hover:bg-tertiary transition-colors duration-fast ${idx % 2 === 0 ? '' : 'bg-secondary/30'
                                                    }`}
                                            >
                                                <td className="py-3 px-4 font-medium text-primary capitalize">{res}</td>
                                                {PERMISSIONS.map(action => {
                                                    const isChecked = permissions[res]?.[action] || false;
                                                    return (
                                                        <td key={action} className="py-3 px-3 text-center">
                                                            <button
                                                                type="button"
                                                                onClick={() => togglePermission(res, action)}
                                                                className={`w-7 h-7 rounded-md border-2 flex items-center justify-center transition-all duration-fast ${isChecked
                                                                        ? 'bg-accent border-accent text-white'
                                                                        : 'border-subtle hover:border-default bg-primary'
                                                                    }`}
                                                                aria-label={`${action} ${res}`}
                                                            >
                                                                {isChecked && <Check size={14} strokeWidth={3} />}
                                                            </button>
                                                        </td>
                                                    );
                                                })}
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <p className="text-xs text-tertiary mt-2">
                            Tip: "Manage" grants full control over a resource.
                        </p>
                    </div>
                </form>

                {/* Footer */}
                <div className="px-6 py-4 border-t border-default flex justify-end gap-3">
                    <button
                        type="button"
                        onClick={onClose}
                        className="btn btn-secondary"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={handleSubmit}
                        disabled={isLoading || !name.trim()}
                        className="btn btn-primary"
                    >
                        {isLoading ? 'Saving...' : (
                            <>
                                <Save size={16} />
                                Save Role
                            </>
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
}
