import { useForm, router, usePage } from '@inertiajs/react';
import AppLayout from '@/layouts/AppLayout';
import { useState } from 'react';
import { useTranslator } from '@/lib/i18n';

type Level = 'none' | 'read' | 'write';

interface PermissionsBundle {
    roles: string[];
    sections: Record<string, string>;
    matrix: Record<string, Record<string, Level | 'read' | 'write'>>;
    isOwner: boolean;
}

interface Props {
    wedding: any;
    collaborators: any[];
    permissions: PermissionsBundle;
}

const ROLE_LABELS: Record<string, string> = {
    partner: 'Partner',
    planner: 'Planner',
    family: 'Family',
    wedding_party: 'Wedding party',
    vendor: 'Vendor',
};

const LEVEL_LABELS: Record<Level, string> = {
    none: '—',
    read: 'View',
    write: 'Edit',
};

export default function Collaborators({ wedding, collaborators, permissions }: Props) {
    const t = useTranslator();
    const { auth } = usePage<any>().props;
    const roleLabel = (role: string) => t(`collaborators.role_${role}`);
    const [showInvite, setShowInvite] = useState(false);
    const [showAdvanced, setShowAdvanced] = useState(false);
    const isCreator = permissions.isOwner ?? auth?.user?.id === wedding.partner_a_id;
    const totalSections = Object.keys(permissions.sections).length;

    // Plain-English summary of what a role can do, derived from its row in the
    // matrix — so the default view stays scannable instead of a 5×13 grid (#25).
    function summarize(perms: Record<string, Level> | undefined) {
        const edit: string[] = [];
        const view: string[] = [];
        Object.entries(permissions.sections).forEach(([key, label]) => {
            const lvl = perms?.[key];
            if (lvl === 'write') edit.push(label);
            else if (lvl === 'read') view.push(label);
        });
        return { edit, view };
    }

    const form = useForm({ email: '', role: 'partner' });

    // Initial matrix state — coerce missing entries to 'none'.
    const initialMatrix: Record<string, Record<string, Level>> = {};
    permissions.roles.forEach((role) => {
        const row: Record<string, Level> = {};
        Object.keys(permissions.sections).forEach((section) => {
            const stored = permissions.matrix?.[role]?.[section];
            row[section] = (stored as Level) ?? 'none';
        });
        initialMatrix[role] = row;
    });

    const matrixForm = useForm({ permissions: initialMatrix });

    function setCell(role: string, section: string, level: Level) {
        matrixForm.setData('permissions', {
            ...matrixForm.data.permissions,
            [role]: { ...matrixForm.data.permissions[role], [section]: level },
        });
    }

    function handleInvite(e: React.FormEvent) {
        e.preventDefault();
        form.post(`/weddings/${wedding.id}/collaborators`, {
            onSuccess: () => { form.reset(); setShowInvite(false); },
            preserveScroll: true,
        });
    }

    function saveMatrix() {
        matrixForm.put(`/weddings/${wedding.id}/permissions`, { preserveScroll: true });
    }

    return (
        <AppLayout wedding={wedding}>
            <div className="max-w-5xl mx-auto px-6 py-10 md:py-14">
                {/* Header */}
                <div className="flex items-end justify-between gap-4 flex-wrap mb-10">
                    <div>
                        <p className="text-[11px] tracking-[0.18em] uppercase text-primary font-semibold mb-2">{t('collaborators.team')}</p>
                        <h1 className="font-serif text-[2.4rem] md:text-[2.8rem] leading-[1.05] text-foreground">{t('collaborators.title')}</h1>
                        <p className="text-[13.5px] text-muted-foreground mt-2 max-w-xl leading-relaxed">
                            Invite the people helping plan the day and pick what each role can see and edit.
                        </p>
                    </div>
                    {isCreator && (
                        <button
                            onClick={() => setShowInvite(true)}
                            className="bg-foreground text-background px-5 py-2.5 rounded-[10px] text-[13.5px] font-medium hover:opacity-90 transition"
                        >
                            {t('collaborators.invite')}
                        </button>
                    )}
                </div>

                {/* Collaborator list */}
                <section className="card-premium p-6 md:p-7 mb-8">
                    <h2 className="font-serif text-[1.35rem] text-foreground mb-5">{t('collaborators.team_members')}</h2>

                    <div className="space-y-2">
                        {/* Owner */}
                        <div className="bg-background/60 border border-border rounded-xl px-4 py-3 flex items-center justify-between">
                            <div>
                                <p className="font-medium text-[14px] text-foreground">{wedding.partner_a?.name ?? 'Owner'}</p>
                                <p className="text-[12px] text-muted-foreground">{wedding.partner_a?.email}</p>
                            </div>
                            <span className="bg-primary/10 text-primary px-2.5 py-1 rounded-full text-[11px] font-medium tracking-wide">
                                {t('collaborators.owner')}
                            </span>
                        </div>

                        {collaborators.map((c) => (
                            <div key={c.id} className="bg-card border border-border rounded-xl px-4 py-3 flex items-center justify-between">
                                <div className="min-w-0">
                                    <p className="font-medium text-[14px] text-foreground truncate">{c.user?.name ?? c.email}</p>
                                    <p className="text-[12px] text-muted-foreground truncate">{c.email}</p>
                                    {!c.accepted_at && (
                                        <span className="inline-block mt-1 text-[10.5px] text-amber-700 bg-amber-50 border border-amber-100 px-2 py-0.5 rounded-full">
                                            {t('collaborators.invitation_pending')}
                                        </span>
                                    )}
                                </div>
                                <div className="flex items-center gap-3">
                                    <span className="text-muted-foreground text-[11.5px] uppercase tracking-[0.08em]">
                                        {ROLE_LABELS[c.role] ? roleLabel(c.role) : c.role}
                                    </span>
                                    {isCreator && (
                                        <button
                                            onClick={() => {
                                                if (!confirm('Remove this collaborator?')) return;
                                                router.delete(`/weddings/${wedding.id}/collaborators/${c.id}`, { preserveScroll: true });
                                            }}
                                            className="text-[11.5px] text-muted-foreground hover:text-danger transition"
                                        >
                                            Remove
                                        </button>
                                    )}
                                </div>
                            </div>
                        ))}

                        {collaborators.length === 0 && (
                            <p className="text-center text-muted-foreground text-[13px] py-6">
                                No collaborators yet. Invite your planner or family above.
                            </p>
                        )}
                    </div>
                </section>

                {/* Role permissions — friendly summary by default, full matrix on demand */}
                <section className="card-premium p-6 md:p-7">
                    <div className="flex items-center justify-between flex-wrap gap-3 mb-5">
                        <div>
                            <h2 className="font-serif text-[1.35rem] text-foreground">{t('collaborators.what_roles_can_do')}</h2>
                            <p className="text-[12.5px] text-muted-foreground mt-1 max-w-xl leading-relaxed">
                                Every role comes with sensible defaults. Owners always have full access.
                            </p>
                        </div>
                        {isCreator && (
                            <button
                                onClick={() => setShowAdvanced((v) => !v)}
                                className="text-[12.5px] font-medium text-primary hover:underline"
                            >
                                {showAdvanced ? t('collaborators.hide_advanced') : t('collaborators.advanced_permissions')}
                            </button>
                        )}
                    </div>

                    {/* Plain-English role cards */}
                    <div className="grid sm:grid-cols-2 gap-3">
                        {permissions.roles.map((role) => {
                            const { edit, view } = summarize(matrixForm.data.permissions[role]);
                            const fullAccess = edit.length === totalSections;
                            return (
                                <div key={role} className="bg-background/60 border border-border rounded-xl p-4">
                                    <p className="font-medium text-[13.5px] text-foreground mb-1">{ROLE_LABELS[role] ? roleLabel(role) : role}</p>
                                    {fullAccess ? (
                                        <p className="text-[12.5px] text-muted-foreground">{t('collaborators.full_access')}</p>
                                    ) : edit.length === 0 && view.length === 0 ? (
                                        <p className="text-[12.5px] text-muted-foreground">{t('collaborators.no_access_default')}</p>
                                    ) : (
                                        <p className="text-[12.5px] text-muted-foreground leading-relaxed">
                                            {edit.length > 0 && <>{t('collaborators.can_edit')} <span className="text-foreground/80">{edit.join(', ')}</span>. </>}
                                            {view.length > 0 && <>{t('collaborators.can_view')} <span className="text-foreground/80">{view.join(', ')}</span>.</>}
                                        </p>
                                    )}
                                </div>
                            );
                        })}
                    </div>

                    {/* Advanced: the full role × section matrix */}
                    {showAdvanced && isCreator && (
                        <div className="mt-6 pt-6 border-t border-border">
                            <div className="flex items-center justify-between flex-wrap gap-3 mb-4">
                                <p className="text-[12.5px] text-muted-foreground max-w-xl leading-relaxed">
                                    Fine-tune what each role can view or edit. Changes apply to current and future invitations.
                                </p>
                                <button
                                    onClick={saveMatrix}
                                    disabled={matrixForm.processing}
                                    className="bg-foreground text-background px-4 py-2 rounded-[10px] text-[12.5px] font-medium hover:opacity-90 transition disabled:opacity-50"
                                >
                                    {matrixForm.processing ? 'Saving…' : t('collaborators.save_permissions')}
                                </button>
                            </div>

                            <div className="overflow-x-auto -mx-2">
                                <table className="w-full border-separate border-spacing-0 text-[12.5px]">
                                    <thead>
                                        <tr>
                                            <th className="text-left font-medium text-muted-foreground py-2 px-3 uppercase tracking-[0.08em] text-[10.5px]">
                                                Section
                                            </th>
                                            {permissions.roles.map((role) => (
                                                <th key={role} className="text-center font-medium text-muted-foreground py-2 px-3 uppercase tracking-[0.08em] text-[10.5px]">
                                                    {ROLE_LABELS[role] ? roleLabel(role) : role}
                                                </th>
                                            ))}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {Object.entries(permissions.sections).map(([sectionKey, sectionLabel]) => (
                                            <tr key={sectionKey} className="border-t border-border">
                                                <td className="py-2.5 px-3 text-foreground text-[13px]">{sectionLabel}</td>
                                                {permissions.roles.map((role) => {
                                                    const cell = matrixForm.data.permissions[role]?.[sectionKey] ?? 'none';
                                                    return (
                                                        <td key={role} className="py-2.5 px-3 text-center">
                                                            <select
                                                                value={cell}
                                                                onChange={(e) => setCell(role, sectionKey, e.target.value as Level)}
                                                                className="bg-card border border-border rounded-md px-2 py-1.5 text-[12px] text-foreground hover:border-foreground/30 transition"
                                                            >
                                                                <option value="none">{LEVEL_LABELS.none}</option>
                                                                <option value="read">{LEVEL_LABELS.read}</option>
                                                                <option value="write">{LEVEL_LABELS.write}</option>
                                                            </select>
                                                        </td>
                                                    );
                                                })}
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}
                </section>
            </div>

            {/* Invite Modal */}
            {showInvite && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
                    <div className="bg-card rounded-2xl p-6 w-full max-w-md shadow-xl">
                        <div className="flex items-center justify-between mb-4">
                            <h2 className="font-serif text-xl">{t('collaborators.invite')}</h2>
                            <button onClick={() => setShowInvite(false)} className="text-muted-foreground">✕</button>
                        </div>
                        <form onSubmit={handleInvite} className="space-y-3">
                            <div>
                                <label className="block text-[11.5px] uppercase tracking-[0.08em] text-muted-foreground font-medium mb-1.5">{t('collaborators.email')}</label>
                                <input
                                    type="email"
                                    value={form.data.email}
                                    onChange={(e) => form.setData('email', e.target.value)}
                                    className="w-full border border-border rounded-lg px-3 py-2 text-[13.5px] focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary/40"
                                    required
                                />
                                {form.errors.email && <p className="text-danger text-[11.5px] mt-1">{form.errors.email}</p>}
                            </div>
                            <div>
                                <label className="block text-[11.5px] uppercase tracking-[0.08em] text-muted-foreground font-medium mb-1.5">{t('collaborators.role')}</label>
                                <select
                                    value={form.data.role}
                                    onChange={(e) => form.setData('role', e.target.value)}
                                    className="w-full border border-border rounded-lg px-3 py-2 text-[13.5px] focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary/40"
                                >
                                    {permissions.roles.map((r) => (
                                        <option key={r} value={r}>{ROLE_LABELS[r] ? roleLabel(r) : r}</option>
                                    ))}
                                </select>
                            </div>
                            <p className="text-[11.5px] text-muted-foreground bg-muted/50 rounded-lg p-3 leading-relaxed">
                                Each role comes with sensible default access. Owners can fine-tune it any time under “Advanced permissions”.
                            </p>
                            <div className="flex gap-3 pt-2">
                                <button type="button" onClick={() => setShowInvite(false)} className="flex-1 border border-border rounded-lg py-2 text-[13px]">
                                    {t('common.cancel')}
                                </button>
                                <button type="submit" disabled={form.processing} className="flex-1 bg-foreground text-background rounded-lg py-2 text-[13px] font-medium disabled:opacity-50">
                                    Send invite
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </AppLayout>
    );
}
