import PermissionController from "@/actions/App/Http/Controllers/PermissionController";
import SelectRoles from "@/components/selects/select-role";
import AppLayout from "@/layouts/app-layout";
// import AppPageHeader from "@/layouts/app-page-header";
import { FlashProps, MetaTags } from "@/types";
import { UserPermission } from "@/types/user";
import { Head, router, useForm, usePage } from "@inertiajs/react";
import { useEffect } from 'react';
import { Button, Card, Col, Container, Form, Row } from "react-bootstrap";
import { PiSpeedometerDuotone } from "react-icons/pi";
import { toast } from "react-toastify";

interface Grouped {
    key: string;
    label: string;
}

interface Props {
    metaTags: MetaTags;
    mode: "create" | "edit";
    grouped: Grouped[];
    permission?: UserPermission;
}

export default function FormBuilder({ metaTags, mode, grouped, permission }: Props) {
    const { flash } = usePage<FlashProps>().props;
    const { data, setData, errors, post, put, processing } = useForm({
        name: '',
        roles: permission?.roles?.map(r => r.id) || [],
        group: grouped && grouped.length ? grouped[0].key : 'new',
        newGroup: '',
    });

    useEffect(() => {
        if (!flash) return;

        // Error message from session
        if (flash.error) {
            const msg = typeof flash.error === 'string' ? flash.error : JSON.stringify(flash.error);
            toast.error(msg);
        }

        // Optional: info or warning
        if (flash.info) {
            const msg = typeof flash.info === 'string' ? flash.info : JSON.stringify(flash.info);
            toast.info(msg);
        }
    }, [flash]);

    // If editing, try to parse existing permission name into action and group
    useEffect(() => {
        if (!permission) return;

        const name = permission.name || '';

        if (name.includes('.')) {
            // dotted format: group.action
            const parts = name.split('.', 2);
            setData('group', String(parts[0]));
            setData('name', parts[1] ?? '');
        } else if (name.includes(' ')) {
            // spaced format: action group (action may contain spaces)
            const pos = name.lastIndexOf(' ');
            const action = name.substring(0, pos);
            const groupKey = name.substring(pos + 1);
            setData('name', action);
            setData('group', String(groupKey));
        } else {
            setData('name', name);
        }
    }, [permission]);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        if (mode === 'create') {
            post(PermissionController.store.url(), {
                onError: (callback) => {
                    toast.error(JSON.stringify(callback, null, 2));
                },
            });
        } else {
            put(PermissionController.update.url(permission!.id), {
                onError: (callback) => {
                    toast.error(JSON.stringify(callback, null, 2));
                },
            });
        }
    }

    return (
        <AppLayout>
            <Head title={metaTags.title} />

            <Container className="p-0">
                <Form onSubmit={handleSubmit}>
                    <Card body className="mb-4 card-theme border border-dashed">
                        <h5 className="mb-4 fw-semibold">Permission Information</h5>

                        <Row>
                            <Col md={6}>
                                <Form.Group className="mb-4 mb-md-0">
                                    <Form.Label htmlFor="name" className="required">Action Name</Form.Label>
                                    <Form.Control
                                        id="name"
                                        name="name"
                                        value={data.name}
                                        onChange={(e) => setData('name', e.target.value)}
                                        isInvalid={!!errors.name}
                                        placeholder="Enter action name (e.g., viewAny, view, create, update, delete)"
                                    />
                                    <Form.Control.Feedback type="invalid">{errors.name}</Form.Control.Feedback>
                                </Form.Group>
                            </Col>
                            <Col md={6}>
                                <Form.Group className="mb-0">
                                    <Form.Label htmlFor="group" className="required">Permission Group</Form.Label>
                                    <Form.Select value={data.group} onChange={(e) => setData('group', String(e.target.value))}>
                                        {grouped && grouped.length > 0 && grouped.map((g) => (
                                            <option key={g.key} value={g.key}>{g.label}</option>
                                        ))}
                                        <option value="new">-- Add new group --</option>
                                    </Form.Select>
                                    <Form.Control.Feedback type="invalid">{errors.group}</Form.Control.Feedback>

                                    {data.group === 'new' && (
                                        <div className="mt-2">
                                            <Form.Control
                                                id="newGroup"
                                                name="newGroup"
                                                value={data.newGroup}
                                                onChange={(e) => setData('newGroup', String(e.target.value))}
                                                placeholder="Enter new group name"
                                                isInvalid={!!errors.newGroup}
                                            />
                                            <Form.Control.Feedback type="invalid">{errors.newGroup}</Form.Control.Feedback>
                                        </div>
                                    )}
                                </Form.Group>
                            </Col>
                        </Row>
                    </Card>

                    <Card body className="mb-4 card-theme border border-dashed">
                        <h5 className="mb-4 fw-semibold">Assign to Roles</h5>
                        <SelectRoles
                            values={data.roles}
                            onChange={(val, checked) => {
                                if (checked) {
                                    setData('roles', Array.from(new Set([...(data.roles || []), val])));
                                } else {
                                    setData('roles', (data.roles || []).filter((r: number) => r !== val));
                                }
                            }}
                        />
                    </Card>

                    <div className="d-flex flex-wrap gap-2">
                        <div className="flex-fill d-grid">
                            <Button type="button" variant="light" onClick={() => router.visit(PermissionController.index.url())} disabled={processing}>Cancel</Button>
                        </div>
                        <div className="flex-fill d-grid">
                            <Button type="submit" variant="primary" disabled={processing}>
                                {mode === 'create' ? 'Submit' : 'Update'}
                            </Button>
                        </div>
                    </div>
                </Form>
            </Container>
        </AppLayout>
    )
}
