import { ActivityLogSidebar } from '@admin/components/activity-log/ActivityLogSidebar';
import { useModelActivityLog } from '@admin/components/activity-log/useModelActivityLog';
import { Form } from '@admin/components/form';
import HeadingSmall from '@admin/components/heading-small';
import TextEditor from '@admin/components/rich-text-editor';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent } from '@admin/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@admin/components/ui/tabs';
import AppLayout from '@admin/layouts/app-layout';
import SettingsLayout from '@admin/layouts/settings/layout';
import { Head, router, useForm } from '@inertiajs/react';
import { Activity, Save } from 'lucide-react';
import { ReactNode, useEffect } from 'react';
import { useFormContext } from 'react-hook-form';

interface Props {
    brandingSettings: { header: string; system_signature: string; user_signature: string; footer: string };
}

function EmailLayoutsIndex({ brandingSettings }: Props) {
    const activityLogCtl = useModelActivityLog();
    const { data, setData, post, processing, reset } = useForm({
        header: brandingSettings.header || '',
        system_signature: brandingSettings.system_signature || '',
        user_signature: brandingSettings.user_signature || '',
        footer: brandingSettings.footer || '',
    });

    // Keep Inertia form state (data) in sync with latest props so Form defaultValues update.
    useEffect(() => {
        setData('header', brandingSettings.header || '');
        setData('footer', brandingSettings.footer || '');
        setData('system_signature', brandingSettings.system_signature || '');
        setData('user_signature', brandingSettings.user_signature || '');
    }, [brandingSettings.header, brandingSettings.footer, brandingSettings.system_signature, brandingSettings.user_signature]);

    const submit = (values: any) => {
        // Post the react-hook-form collected values directly (do not rely on inertia useForm internal data)
        router.post(route('settings.email.branding.update'), values, { preserveScroll: true });
    };

    // Sync incoming props to form (ensures editors pick up initial content)
    useEffect(() => {
        (reset as any)({
            header: brandingSettings.header || '',
            system_signature: brandingSettings.system_signature || '',
            user_signature: brandingSettings.user_signature || '',
            footer: brandingSettings.footer || '',
        });
    }, [brandingSettings.header, brandingSettings.system_signature, brandingSettings.user_signature, brandingSettings.footer, reset]);

    return (
        <>
            <Head title="Email Layout" />
            <SettingsLayout tab="platform">
                <Card className="mx-auto w-full space-y-5 border px-3 py-3 sm:px-5">
                    <div className="mb-3 flex flex-col gap-2 border-b pb-3 sm:flex-row sm:items-center sm:justify-between">
                        <HeadingSmall title="Email Layout" description="Manage header, footer, and system/user signatures." />
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() =>
                                activityLogCtl.show({
                                    modelClass: 'Setting',
                                    title: 'Email Branding Activity',
                                    action: 'email_branding_settings_updated',
                                })
                            }
                        >
                            <Activity className="mr-1 h-4 w-4" /> Activity
                        </Button>
                    </div>
                    <CardContent className="w-full p-0">
                        <Tabs defaultValue="layout" className="w-full">
                            <TabsList className="mb-5 inline-flex w-full items-center gap-2 rounded-full bg-muted/60 px-2 py-1 sm:w-auto">
                                <TabsTrigger
                                    value="layout"
                                    className="flex-1 rounded-full px-3 py-2 text-sm font-medium transition data-[state=active]:bg-background data-[state=active]:text-primary data-[state=active]:shadow sm:flex-none sm:px-5"
                                >
                                    Layout
                                </TabsTrigger>
                                <TabsTrigger
                                    value="signature"
                                    className="flex-1 rounded-full px-3 py-2 text-sm font-medium transition data-[state=active]:bg-background data-[state=active]:text-primary data-[state=active]:shadow sm:flex-none sm:px-5"
                                >
                                    Signature
                                </TabsTrigger>
                            </TabsList>
                            <TabsContent value="layout" className="mt-0 focus-visible:outline-none">
                                <div className="mb-4 rounded-md border bg-muted/30 px-4 py-3 text-xs leading-relaxed text-muted-foreground">
                                    <p className="mb-1 font-medium text-foreground">How layout blocks render:</p>
                                    <ul className="ml-4 list-disc space-y-1">
                                        <li>
                                            <span className="font-semibold">Header</span> appears at the very top of every branded email before the
                                            template body. Ideal for logo, brand bar, or greeting banner.
                                        </li>
                                        <li>
                                            <span className="font-semibold">Footer</span> sits below the template body and before unsubscribe or
                                            compliance links. Use for legal text, CTA strips, or brand links.
                                        </li>
                                        <li>
                                            Signatures (managed under the Signature tab) are appended after the footer: system first, then (if
                                            available) the user-specific signature.
                                        </li>
                                    </ul>
                                    <p className="mt-2">Avoid embedding full page styling here—keep it structural so templates remain flexible.</p>
                                </div>
                                <Form submitHandler={submit} defaultValues={data} formClassNames="space-y-4 w-full flex-1">
                                    <div className="w-sm md:w-xl lg:w-2xl xl:w-3xl 2xl:w-7xl">
                                        <LayoutEditors />
                                    </div>
                                    <div className="flex items-center gap-2 pt-2">
                                        <Button type="submit" disabled={processing}>
                                            <Save className="h-4 w-4" />
                                            Save Changes
                                        </Button>
                                    </div>
                                </Form>
                            </TabsContent>
                            <TabsContent value="signature" className="mt-0 focus-visible:outline-none">
                                <div className="mb-4 rounded-md border bg-muted/30 px-4 py-3 text-xs leading-relaxed text-muted-foreground">
                                    <p className="mb-1 font-medium text-foreground">Signature layering logic:</p>
                                    <ol className="ml-4 list-decimal space-y-1">
                                        <li>
                                            <span className="font-semibold">System Signature</span>: Organization-wide block (branding, corporate
                                            identity, mandatory legal or contact information).
                                        </li>
                                        <li>
                                            <span className="font-semibold">User Signature</span>: Personal block (name, role, direct contact methods)
                                            appended under the system signature when present.
                                        </li>
                                    </ol>
                                    <p className="mt-2">
                                        If a user signature is empty, only the system signature is used. Keep images lightweight (hosted & sized) to
                                        avoid deliverability penalties.
                                    </p>
                                </div>
                                <Form submitHandler={submit} defaultValues={data} formClassNames="space-y-4">
                                    <div className="w-sm md:w-xl lg:w-2xl xl:w-3xl 2xl:w-7xl">
                                        <SignatureEditor />
                                    </div>
                                    <div className="flex items-center gap-2 pt-2">
                                        <Button type="submit" disabled={processing}>
                                            <Save className="h-4 w-4" />
                                            Save Changes
                                        </Button>
                                    </div>
                                </Form>
                            </TabsContent>
                        </Tabs>
                    </CardContent>
                </Card>
                <ActivityLogSidebar
                    open={activityLogCtl.open}
                    onOpenChange={activityLogCtl.setOpen}
                    modelClass={activityLogCtl.modelClass}
                    modelId={activityLogCtl.modelId}
                    title={activityLogCtl.title}
                    action={activityLogCtl.action}
                    actions={activityLogCtl.actions}
                />
            </SettingsLayout>
        </>
    );
}

EmailLayoutsIndex.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Settings', href: '/settings/email' },
            { title: 'Email Layout', href: '#' },
        ]}
        title="Email Layout"
    >
        {page}
    </AppLayout>
);

export default EmailLayoutsIndex;

const LayoutEditors = () => {
    const { watch, setValue } = useFormContext();
    const header = watch('header') || '';
    const footer = watch('footer') || '';

    return (
        <div className="flex flex-col gap-4 sm:gap-6">
            {/* Header Panel */}
            <section className="flex w-full flex-col overflow-hidden rounded-lg border bg-card/50 shadow-sm backdrop-blur-sm">
                <header className="flex items-start justify-between gap-3 border-b bg-background/60 px-3 py-2.5 sm:px-4">
                    <div>
                        <h3 className="text-sm font-semibold tracking-wide">Header</h3>
                        <p className="mt-0.5 text-[11px] text-muted-foreground">Appears above the email body (logo / banner / greeting).</p>
                    </div>
                    {/* Actions/stats removed */}
                </header>
                <div className="min-h-[200px] w-full p-1 sm:min-h-[250px] sm:p-2">
                    <TextEditor name="header" />
                </div>
            </section>

            {/* Footer Panel */}
            <section className="flex w-full flex-col overflow-hidden rounded-lg border bg-card/50 shadow-sm ring-1 ring-black/5 backdrop-blur-sm">
                <header className="flex items-start justify-between gap-3 border-b bg-background/60 px-3 py-2.5 sm:px-4">
                    <div>
                        <h3 className="text-sm font-semibold tracking-wide">Footer</h3>
                        <p className="mt-0.5 text-[11px] text-muted-foreground">Comes after the email body (legal, links, brand).</p>
                    </div>
                    {/* Actions/stats removed */}
                </header>

                <div className="min-h-[200px] w-full p-1 sm:min-h-[250px] sm:p-2">
                    <TextEditor name="footer" />
                </div>
            </section>
        </div>
    );
};

// Signature editor component with tighter spacing & stats inline
const SignatureEditor = () => {
    const { watch, setValue } = useFormContext();
    const systemSig = watch('system_signature') || '';
    const userSig = watch('user_signature') || '';
    const strip = (html: string) => (html || '').replace(/<[^>]+>/g, '').trim();
    // const systemPlain = strip(systemSig);
    // const userPlain = strip(userSig);

    return (
        <div className="flex flex-col gap-4 sm:gap-6">
            <section className="flex flex-col overflow-hidden rounded-lg border bg-card/50 shadow-sm ring-1 ring-black/5 backdrop-blur-sm">
                <header className="flex items-start justify-between gap-3 border-b bg-background/60 px-3 py-2.5 sm:px-4">
                    <div>
                        <h3 className="text-sm font-semibold tracking-wide">System Signature</h3>
                        <p className="mt-0.5 text-[11px] text-muted-foreground">Global footer signature (company legal/contact info).</p>
                    </div>
                    {/* Actions/stats removed */}
                </header>
                <div className="p-2 sm:p-3">
                    <div className="min-h-[140px] w-full rounded-md border bg-background p-1 sm:min-h-[160px] sm:p-2">
                        <TextEditor name="system_signature" />
                    </div>
                </div>
            </section>
            <section className="flex flex-col overflow-hidden rounded-lg border bg-card/50 shadow-sm ring-1 ring-black/5 backdrop-blur-sm">
                <header className="flex items-start justify-between gap-3 border-b bg-background/60 px-3 py-2.5 sm:px-4">
                    <div>
                        <h3 className="text-sm font-semibold tracking-wide">User Signature</h3>
                        <p className="mt-0.5 text-[11px] text-muted-foreground">Optional per-user signature (name, role, direct contacts).</p>
                    </div>
                    {/* Actions/stats removed */}
                </header>
                <div className="p-2 sm:p-3">
                    <div className="min-h-[140px] w-full rounded-md border bg-background p-1 sm:min-h-[160px] sm:p-2">
                        <TextEditor name="user_signature" />
                    </div>
                </div>
            </section>
        </div>
    );
};
