import { router } from '@inertiajs/react';
import { useState } from 'react';
import { AlertTriangle, Loader2 } from 'lucide-react';
import { useToast } from '@/Components/Toast';
import { FormInput, FormSelect } from '@/Components/Form/FormControls';

/**
 * The four related-data actions from legacy listuseredit.php's bottom half.
 *
 * These are NOT ordinary deletes. `userdivision.IsHeadDiv` and `userprincipal.IsHeadDiv` feed
 * User::headDivisionIds() / headPrincipalIds(), which decide which companies and market surveys
 * a user can see; `company.UserIDSales` decides account ownership. Clearing them silently
 * changes what other people can see.
 *
 * So each action requires the operator to TYPE a confirmation word before the button enables —
 * legacy used a bare window.confirm(), which is one reflexive Enter away from wiping a pivot.
 * Each panel also lists the rows it is about to affect, so the blast radius is visible first.
 */

const DANGER_BTN =
    'inline-flex h-8 items-center justify-center gap-1.5 rounded-lg border border-destructive/40 bg-destructive/5 px-3 text-xs font-bold text-destructive transition-colors hover:bg-destructive/15 disabled:cursor-not-allowed disabled:opacity-50';

const CANCEL_BTN =
    'inline-flex h-9 items-center justify-center rounded-lg border border-input bg-card px-4 text-xs font-bold text-foreground transition-colors hover:border-primary hover:text-primary';

const CONFIRM_BTN =
    'inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-destructive px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50';

const CONFIRM_WORD = 'HAPUS';

/** Modal requiring the operator to type CONFIRM_WORD. Split footer: cancel left, danger right. */
function ConfirmDialog({
    title, description, rowCount, onCancel, onConfirm, processing, children, confirmLabel,
    // Extra precondition beyond the typed word — the reassign dialog also needs a target sales.
    extraValid = true,
}) {
    const [typed, setTyped] = useState('');
    const armed = typed.trim().toUpperCase() === CONFIRM_WORD && extraValid;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true">
            <div className="w-full max-w-md rounded-xl border border-border bg-card p-5 shadow-lg">
                <div className="mb-3 flex items-start gap-2.5">
                    <AlertTriangle className="mt-0.5 size-5 shrink-0 text-destructive" aria-hidden="true" />
                    <div>
                        <h3 className="text-sm font-semibold text-foreground">{title}</h3>
                        <p className="mt-1 text-xs text-muted-foreground">{description}</p>
                    </div>
                </div>

                <p className="mb-3 rounded-lg bg-secondary/50 px-3 py-2 text-xs text-foreground">
                    <strong>{rowCount}</strong> baris akan terpengaruh.
                </p>

                {children}

                <label className="mb-4 block text-xs font-medium text-foreground">
                    Ketik <span className="font-bold text-destructive">{CONFIRM_WORD}</span> untuk konfirmasi
                    <FormInput
                        value={typed}
                        onChange={(e) => setTyped(e.target.value)}
                        className="mt-1"
                        autoFocus
                        aria-label={`Ketik ${CONFIRM_WORD} untuk konfirmasi`}
                    />
                </label>

                {/* Split footer — cancel far from the destructive action, per the locked convention. */}
                <div className="flex items-center justify-between gap-2">
                    <button type="button" onClick={onCancel} className={CANCEL_BTN}>Batal</button>
                    <button
                        type="button"
                        disabled={!armed || processing}
                        onClick={onConfirm}
                        className={CONFIRM_BTN}
                    >
                        {processing ? <><Loader2 className="mr-1 size-4 animate-spin" />Memproses...</> : (confirmLabel ?? 'Hapus')}
                    </button>
                </div>
            </div>
        </div>
    );
}

/** One panel: title, current rows, and the destructive action that clears them. */
function Panel({ title, description, rows, renderRow, emptyText, actionLabel, onAction }) {
    return (
        <section className="rounded-xl border border-border bg-card p-5 shadow-sm">
            <header className="mb-3 flex items-start justify-between gap-3 border-b border-border pb-3">
                <div>
                    <h2 className="text-sm font-semibold text-foreground">
                        {title} <span className="text-muted-foreground">({rows.length})</span>
                    </h2>
                    <p className="mt-0.5 text-xs text-muted-foreground">{description}</p>
                </div>
                <button type="button" onClick={onAction} disabled={rows.length === 0} className={DANGER_BTN}>
                    {actionLabel}
                </button>
            </header>

            {rows.length === 0 ? (
                <p className="text-xs text-muted-foreground">{emptyText}</p>
            ) : (
                <ul className="grid gap-1.5 sm:grid-cols-2">
                    {rows.map(renderRow)}
                </ul>
            )}
        </section>
    );
}

const Chip = ({ children, tone }) => (
    <span className={`ml-1.5 rounded-full px-1.5 py-0.5 text-[10px] font-semibold ${
        tone === 'primary' ? 'bg-primary/10 text-primary' : 'bg-secondary text-muted-foreground'
    }`}>
        {children}
    </span>
);

export default function RelatedPanels({ employee, related, salesOptions }) {
    const { show: showToast } = useToast();
    const [dialog, setDialog] = useState(null);       // 'divisions' | 'principals' | 'access' | 'companies'
    const [processing, setProcessing] = useState(false);
    const [targetSales, setTargetSales] = useState('');

    const close = () => { setDialog(null); setTargetSales(''); };

    const run = (routeName, data = {}) => {
        setProcessing(true);
        router.post(route(routeName, employee.ID), data, {
            preserveScroll: true,
            onSuccess: () => close(),
            onError: (errors) => showToast(Object.values(errors)[0] ?? 'Action failed.', 'error'),
            onFinish: () => setProcessing(false),
        });
    };

    return (
        <div className="grid gap-4">
            <Panel
                title="Sales Division"
                description="Menentukan divisi yang dipegang employee. IsHeadDiv memengaruhi company & market survey yang bisa dilihat."
                rows={related.divisions}
                emptyText="Employee ini tidak terhubung ke divisi mana pun."
                actionLabel="Hapus semua"
                onAction={() => setDialog('divisions')}
                renderRow={(d) => (
                    <li key={d.ID} className="rounded-lg bg-secondary/40 px-2.5 py-1.5 text-xs text-foreground">
                        {d.DivisionName ?? '—'}
                        {d.IsHeadDiv && <Chip tone="primary">Head Div</Chip>}
                        {d.IsSendEmail && <Chip>Email</Chip>}
                    </li>
                )}
            />

            <Panel
                title="PM & Principal"
                description="Principal yang dipegang employee. IsHeadDiv memengaruhi market survey PM."
                rows={related.principals}
                emptyText="Employee ini tidak terhubung ke principal mana pun."
                actionLabel="Hapus semua"
                onAction={() => setDialog('principals')}
                renderRow={(p) => (
                    <li key={p.ID} className="rounded-lg bg-secondary/40 px-2.5 py-1.5 text-xs text-foreground">
                        {p.PrincipalName ?? '—'}
                        {p.IsHeadDiv && <Chip tone="primary">Head Div</Chip>}
                        {p.IsMM && <Chip>MM</Chip>}
                    </li>
                )}
            />

            <Panel
                title="Company Access (Others)"
                description="Akses tambahan ke company milik sales lain."
                rows={related.companyAccess}
                emptyText="Tidak ada akses tambahan."
                actionLabel="Hapus semua"
                onAction={() => setDialog('access')}
                renderRow={(c) => (
                    <li key={c.ID} className="rounded-lg bg-secondary/40 px-2.5 py-1.5 text-xs text-foreground">
                        {c.CompanyName ?? '—'}
                    </li>
                )}
            />

            <Panel
                title="Company (sebagai Sales)"
                description="Company yang dipegang employee ini. Dipindahkan ke sales lain, bukan dihapus."
                rows={related.companies}
                emptyText="Employee ini tidak memegang company."
                actionLabel="Pindahkan ke sales lain"
                onAction={() => setDialog('companies')}
                renderRow={(c) => (
                    <li key={c.ID} className="rounded-lg bg-secondary/40 px-2.5 py-1.5 text-xs text-foreground">
                        {c.CompanyName ?? '—'}
                    </li>
                )}
            />

            {dialog === 'divisions' && (
                <ConfirmDialog
                    title="Hapus semua Sales Division?"
                    description="Semua baris userdivision employee ini akan di-soft-delete. Ini mengubah company & market survey yang bisa dilihat employee."
                    rowCount={related.divisions.length}
                    processing={processing}
                    onCancel={close}
                    onConfirm={() => run('employees.clear-divisions')}
                />
            )}

            {dialog === 'principals' && (
                <ConfirmDialog
                    title="Hapus semua PM & Principal?"
                    description="Semua baris userprincipal employee ini akan di-soft-delete. Ini mengubah market survey PM yang bisa dilihat employee."
                    rowCount={related.principals.length}
                    processing={processing}
                    onCancel={close}
                    onConfirm={() => run('employees.clear-principals')}
                />
            )}

            {dialog === 'access' && (
                <ConfirmDialog
                    title="Hapus semua Company Access?"
                    description="Semua baris companyaccessothers employee ini akan di-soft-delete."
                    rowCount={related.companyAccess.length}
                    processing={processing}
                    onCancel={close}
                    onConfirm={() => run('employees.clear-company-access')}
                />
            )}

            {dialog === 'companies' && (
                <ConfirmDialog
                    title="Pindahkan company ke sales lain?"
                    description="Semua company yang dipegang employee ini akan dipindahkan ke sales yang dipilih. Company TIDAK dihapus."
                    rowCount={related.companies.length}
                    processing={processing}
                    confirmLabel="Pindahkan"
                    extraValid={targetSales !== ''}
                    onCancel={close}
                    onConfirm={() => run('employees.reassign-companies', { UserIDSales: Number(targetSales) })}
                >
                    <label className="mb-4 block text-xs font-medium text-foreground">
                        Sales tujuan
                        <FormSelect
                            value={targetSales}
                            onChange={(e) => setTargetSales(e.target.value)}
                            className="mt-1"
                            aria-label="Sales tujuan"
                        >
                            <option value="">— Pilih sales —</option>
                            {(salesOptions ?? []).map((s) => (
                                <option key={s.ID} value={s.ID}>{s.Nama}</option>
                            ))}
                        </FormSelect>
                    </label>
                </ConfirmDialog>
            )}
        </div>
    );
}
