import { ActivityLogSidebar } from '@admin/components/activity-log/ActivityLogSidebar';
import { useModelActivityLog } from '@admin/components/activity-log/useModelActivityLog';
import { Form, FormField } from '@admin/components/form';
import HeadingSmall from '@admin/components/heading-small';
import TextEditor, { TextEditorRef } from '@admin/components/rich-text-editor';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@admin/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@admin/components/ui/dialog';
import { Tooltip, TooltipContent, TooltipTrigger } from '@admin/components/ui/tooltip';
import AppLayout from '@admin/layouts/app-layout';
import SettingsLayout from '@admin/layouts/settings/layout';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { Activity, ArrowLeft } from 'lucide-react';
import { useRef, useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { toast } from 'sonner';

export default function Edit({ emailTemplate, availableVariable }: { emailTemplate: any; availableVariable: any }) {
    const { setValue, watch } = useFormContext() || ({} as any);
    const textEditorRef = useRef<TextEditorRef>(null);
    const activityLogCtl = useModelActivityLog();
    const page = usePage<any>();
    const companyName = (page?.props as any)?.settings?.company_name;
    const defaultValues = {
        name: emailTemplate.name || '',
        content: {
            body: emailTemplate.content?.body || '',
            subject: emailTemplate.content?.subject || '',
        },
        from_name: companyName || emailTemplate.from_name || '',
    };
    const [testOpen, setTestOpen] = useState(false);
    const [testEmail, setTestEmail] = useState('');
    const [testing, setTesting] = useState(false);

    // Removed flash-driven auto close; handled directly in onSuccess for reliability

    const handleSubmit = async (values: any) => {
        router.put(`/settings/email-templates/${emailTemplate.uid}`, values, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Template updated!');
            },
            onError: () => toast.error('Update failed!'),
        });
    };

    const submitTestEmail = () => {
        if (!testEmail) {
            toast.error('Please enter a test email');
            return;
        }
        setTesting(true);
        router.post(
            route('settings.email-templates.test', { uid: emailTemplate.uid }),
            { email: testEmail },
            {
                preserveScroll: true,
                preserveState: true,
                onSuccess: (page) => {
                    const flash = (page.props as any)?.flash;
                    toast.success(flash?.success || 'Test email sent');
                    setTestOpen(false);
                    setTestEmail('');
                },
                onError: (errors: any) => {
                    if (errors?.email) toast.error(errors.email);
                    if (errors?.test_email) toast.error(errors.test_email);
                },
                onFinish: () => setTesting(false),
            },
        );
    };

    const handleVariableClick = (variable: string) => {
        if (textEditorRef.current) {
            // Insert the variable at the current cursor position
            textEditorRef.current.insertTextAtCursor(` ${variable} `);
        } else {
            // Fallback to the old method if ref is not available
            const currentContent = watch('content.body') || '';
            const newContent = currentContent + ' ' + variable;
            setValue('content.body', newContent);
        }
    };
    return (
        <>
            <Head title={`Edit Template: ${emailTemplate.name}`} />
            <SettingsLayout tab="platform">
                <div className="space-y-6">
                    <div className="flex w-full flex-col items-start gap-4 lg:flex-row">
                        {/* Main Form - Left Column */}
                        <div className="w-xl flex-1 space-y-6 rounded-lg">
                            <Card className="rounded-lg border px-0 py-3">
                                <div className="flex items-start justify-between gap-5 border-b px-4">
                                    <div className="flex w-full items-start gap-5">
                                        <Link
                                            href={route('settings.email-templates.index')}
                                            className="flex h-10 w-10 cursor-pointer items-center justify-center rounded-lg border bg-brand-100 transition-colors hover:bg-brand-200"
                                            title="Back to Email Templates"
                                        >
                                            <ArrowLeft size={15} color="#020617" />
                                        </Link>
                                        <HeadingSmall
                                            className="mb-0 border-none pb-4"
                                            title={emailTemplate.name}
                                            description={emailTemplate.description || ''}
                                        />
                                    </div>
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onClick={() =>
                                            activityLogCtl.show({
                                                modelClass: 'Setting',
                                                title: 'Email Templates Activity',
                                                action: 'email_templates_updated',
                                            })
                                        }
                                    >
                                        <Activity className="mr-1 h-4 w-4" /> Activity
                                    </Button>
                                </div>
                                <CardContent className="px-2 py-4 md:px-4">
                                    <Form defaultValues={defaultValues} submitHandler={handleSubmit} formClassNames="space-y-6">
                                        {/* Hidden retained name field (backend requires name) */}
                                        <input type="hidden" name="name" value={emailTemplate.name} />
                                        <FormField
                                            name="content.subject"
                                            label="Subject Line"
                                            type="text"
                                            required
                                            placeholder="Enter Subject Line"
                                        />
                                        <FormField
                                            name="from_name"
                                            label="From Name (override)"
                                            type="text"
                                            placeholder={companyName || emailTemplate.from_name || 'Company Name'}
                                        />
                                        <div className="mb-5 border-b border-white">
                                            <div className="mb-2 space-y-2">
                                                <label htmlFor="content.body" className="block text-sm font-medium">
                                                    Body
                                                </label>
                                                <TextEditor name="content.body" ref={textEditorRef} />
                                            </div>
                                        </div>

                                        <div className="mt-6 flex items-center gap-2">
                                            <Button type="submit" className="bg-success hover:bg-brand-800">
                                                Save Changes
                                            </Button>
                                            <Button type="button" variant="outline" onClick={() => setTestOpen(true)}>
                                                Test Email
                                            </Button>
                                        </div>
                                    </Form>
                                </CardContent>
                            </Card>
                        </div>
                        {/* Variables Panel - Right Column */}
                        <div className="w-full space-y-6 rounded-lg lg:w-60 lg:flex-shrink-0 2xl:w-80">
                            {availableVariable?.map((list: any, index: number) => (
                                <Card key={index} className="border transition-all duration-200">
                                    <CardHeader className="px-3 py-3 lg:px-2 lg:py-2">
                                        <CardTitle className="flex items-center gap-2 text-sm font-semibold">{list?.key}</CardTitle>
                                    </CardHeader>
                                    <CardContent className="px-3 lg:px-2">
                                        <div className="flex flex-wrap gap-2">
                                            {list?.value?.map((variable: any, varIndex: number) => (
                                                <Tooltip key={varIndex}>
                                                    <TooltipTrigger asChild>
                                                        <div
                                                            className="focus:ring-opacity-50 inline-flex cursor-pointer items-center rounded-lg border px-2 py-1.5 text-xs font-medium text-gray-700 transition-all duration-200 hover:scale-105 hover:border-brand-100 hover:bg-blue-100 hover:text-success focus:ring-2 focus:ring-success focus:outline-none active:scale-95 sm:px-3"
                                                            onClick={() => handleVariableClick(variable?.variable)}
                                                        >
                                                            <p className="truncate">{variable?.variable}</p>
                                                        </div>
                                                    </TooltipTrigger>
                                                    <TooltipContent
                                                        side="left"
                                                        className="max-w-xs rounded-lg border border-gray-200 bg-white p-3 shadow-lg"
                                                    >
                                                        <div className="space-y-2">
                                                            <div className="flex items-start gap-2">
                                                                <div>
                                                                    <p className="text-sm font-semibold text-gray-900">{variable?.variable_name}</p>
                                                                    <p className="mt-1 text-xs leading-relaxed text-gray-600">
                                                                        {variable?.variable_description}
                                                                    </p>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </TooltipContent>
                                                </Tooltip>
                                            ))}
                                        </div>
                                    </CardContent>
                                </Card>
                            ))}
                        </div>
                    </div>
                </div>
            </SettingsLayout>
            <TestEmailDialog
                open={testOpen}
                onOpenChange={setTestOpen}
                value={testEmail}
                onChange={setTestEmail}
                onSubmit={submitTestEmail}
                loading={testing}
            />

            <ActivityLogSidebar
                open={activityLogCtl.open}
                onOpenChange={activityLogCtl.setOpen}
                modelClass={activityLogCtl.modelClass}
                modelId={activityLogCtl.modelId}
                title={activityLogCtl.title}
                action={activityLogCtl.action}
                actions={activityLogCtl.actions}
            />
        </>
    );
}

// Test Email Dialog
// Positioned outside main component return to keep code organized

function TestEmailDialog({
    open,
    onOpenChange,
    value,
    onChange,
    onSubmit,
    loading,
}: {
    open: boolean;
    onOpenChange: (o: boolean) => void;
    value: string;
    onChange: (v: string) => void;
    onSubmit: () => void;
    loading: boolean;
}) {
    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Send Test Email</DialogTitle>
                    <DialogDescription>Enter a recipient email address to receive a test rendering of this template.</DialogDescription>
                </DialogHeader>
                <div className="space-y-4">
                    <div className="space-y-2">
                        <label className="text-sm font-medium" htmlFor="test-email-input">
                            Recipient Email
                        </label>
                        <input
                            id="test-email-input"
                            type="email"
                            className="w-full rounded-md border px-3 py-2 text-sm focus:ring-2 focus:ring-success focus:outline-none"
                            placeholder="user@example.com"
                            value={value}
                            onChange={(e) => onChange(e.target.value)}
                        />
                    </div>
                </div>
                <DialogFooter className="mt-4">
                    <Button variant="outline" type="button" onClick={() => onOpenChange(false)} disabled={loading}>
                        Cancel
                    </Button>
                    <Button type="button" onClick={onSubmit} disabled={loading} className="bg-success hover:bg-brand-800">
                        {loading ? 'Sending...' : 'Send Test'}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}

Edit.layout = (page: React.ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Settings', href: '/settings/global_settings' },
            { title: 'Email Templates', href: '/settings/email-templates' },
        ]}
        title="Edit Email Template"
    >
        {page}
    </AppLayout>
);
