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 { Button } from '@admin/components/ui/button';
import { Card, CardContent } from '@admin/components/ui/card';
import AppLayout from '@admin/layouts/app-layout';
import SettingsLayout from '@admin/layouts/settings/layout';
import { Head, router, useForm as useInertiaForm, usePage } from '@inertiajs/react';
import { Activity, Save } from 'lucide-react';
import { ReactNode } from 'react';
import { useFormContext } from 'react-hook-form';
import { toast } from 'sonner';

interface Props {
    emailSettings: {
        mail_driver: string;
        mail_from_address: string;
        mail_from_name: string;
        mail_host: string;
        mail_port: number;
        mail_username: string;
        mail_password: string;
        mail_encryption: string;
    };
    brandingSettings: {
        header: string;
        system_signature: string;
        user_signature: string;
        footer: string;
    };
}

export default function Index({ emailSettings, brandingSettings }: Props) {
    const activityLogCtl = useModelActivityLog();
    const page = usePage<any>();
    const handleTestMail = () => {
        router.post(
            route('settings.email.test'),
            {},
            {
                preserveScroll: true,
                onSuccess: () => {
                    const props: any = usePage().props;
                    const success = props?.flash?.success;
                    if (success) toast.success(success);
                    const err = props?.errors?.email_test;
                    if (err) toast.error(err);
                },
                onError: (errors: any) => {
                    if (errors?.email_test) toast.error(errors.email_test);
                },
            },
        );
    };

    // Main email settings form state (custom Form)
    const emailDefaultValues = {
        mail_driver: emailSettings.mail_driver || 'smtp',
        mail_from_address: emailSettings.mail_from_address || null,
        mail_from_name: emailSettings.mail_from_name || null,
        mail_host: emailSettings.mail_host || null,
        mail_port: emailSettings.mail_port || 587,
        mail_username: emailSettings.mail_username || null,
        mail_password: emailSettings.mail_password || null,
        mail_encryption: emailSettings.mail_encryption || 'tls',
    };

    const handleSubmitEmailSettings = async (values: any) => {
        router.post(route('settings.email.update'), values, { preserveScroll: true });
    };
    useInertiaForm({
        email_header: null, // default values or fetched from props
        email_signature: null,
        email_footer: null,
    });

    // Branding form state (custom Form)
    const brandingDefaultValues = {
        header: brandingSettings.header || null,
        system_signature: brandingSettings.system_signature || null,
        user_signature: brandingSettings.user_signature || null,
        footer: brandingSettings.footer || null,
    };

    const handleSubmitEmailBranding = async (values: any) => {
        router.post(route('settings.email_brand.update'), values);
    };

    return (
        <>
            <Head title="Email Settings" />
            <SettingsLayout tab="platform">
                <div className="space-y-6">
                    <Card className="w-full rounded-lg border border-gray-200 px-5 py-3">
                        <div className="mb-3 flex items-center justify-between border-b">
                            <HeadingSmall title="Email Settings" description="Update your application's email configuration" />

                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() =>
                                    activityLogCtl.show({
                                        modelClass: 'Setting',
                                        title: 'Email Branding Activity',
                                        action: 'email_branding_updated',
                                    })
                                }
                            >
                                <Activity className="mr-1 h-4 w-4" /> Activity
                            </Button>
                        </div>

                        {/* Configurations */}
                        <CardContent className="w-full px-0">
                            <Form
                                defaultValues={emailDefaultValues}
                                submitHandler={handleSubmitEmailSettings}
                                externalErrors={(page.props as any).errors}
                                formClassNames="space-y-6"
                            >
                                <div className="grid gap-6 *:grid-cols-1 md:grid-cols-2">
                                    <FormField
                                        name="mail_driver"
                                        label="Mail Driver"
                                        type="select"
                                        required
                                        options={[
                                            { value: 'smtp', label: 'SMTP' },
                                            { value: 'ses', label: 'Amazon SES' },
                                            { value: 'mailgun', label: 'Mailgun' },
                                            { value: 'log', label: 'Log (Development)' },
                                            { value: 'sendmail', label: 'Sendmail' },
                                        ]}
                                    />
                                    <FormField name="mail_from_address" label="From Email" type="email" placeholder="example@example.com" required />
                                    <FormField name="mail_from_name" label="From Name" type="text" placeholder="Your App Name" required />

                                    <TransportSpecificFields />
                                </div>
                                <div className="flex flex-row flex-nowrap items-center gap-2">
                                    <Button type="submit" className="shrink-0 whitespace-nowrap">
                                        <Save className="h-4 w-4" />
                                        Save Changes
                                    </Button>
                                    <Button
                                        type="button"
                                        variant="outline"
                                        className="shrink-0 text-sm whitespace-nowrap text-success"
                                        onClick={handleTestMail}
                                    >
                                        Test Mail
                                    </Button>
                                </div>
                            </Form>
                        </CardContent>
                    </Card>
                </div>
            </SettingsLayout>
            <ActivityLogSidebar
                open={activityLogCtl.open}
                onOpenChange={activityLogCtl.setOpen}
                modelClass={activityLogCtl.modelClass}
                modelId={activityLogCtl.modelId}
                title={activityLogCtl.title}
                action={activityLogCtl.action}
                actions={activityLogCtl.actions}
            />
        </>
    );
}

// Renders transport specific credential fields based on selected driver
function TransportSpecificFields() {
    const { watch } = useFormContext();
    const driver = watch('mail_driver');

    if (!driver) return null;

    switch (driver) {
        case 'smtp':
            return (
                <>
                    <FormField name="mail_host" label="Mail Host" type="text" placeholder="smtp.example.com" required />
                    <FormField name="mail_port" label="Mail Port" type="number" placeholder="587" required />
                    <FormField name="mail_username" label="Username" type="text" placeholder="username" required />
                    <FormField name="mail_password" label="Password" type="password" placeholder="password" required />
                    <FormField name="mail_encryption" label="Encryption" type="text" placeholder="tls / ssl / null" required />
                </>
            );
        case 'ses':
            // SES via Laravel uses env creds; allow optional region override fields in future
            return (
                <>
                    <FormField name="mail_host" label="Endpoint (optional)" type="text" placeholder="email.us-east-1.amazonaws.com" />
                    <FormField name="mail_encryption" label="Encryption" type="text" placeholder="tls / ssl / null" />
                </>
            );
        case 'mailgun':
            return (
                <>
                    <FormField name="mail_host" label="Mailgun Host" type="text" placeholder="smtp.mailgun.org" />
                    <FormField name="mail_username" label="SMTP Username" type="text" placeholder="postmaster@domain" />
                    <FormField name="mail_password" label="SMTP Password" type="password" placeholder="password" />
                    <FormField name="mail_encryption" label="Encryption" type="text" placeholder="tls / ssl" />
                </>
            );
        case 'sendmail':
            return (
                <>
                    <FormField name="mail_host" label="Sendmail Path" type="text" placeholder="/usr/sbin/sendmail -bs -i" />
                </>
            );
        case 'log':
            return <>{/* No extra credentials needed for log driver */}</>;
        default:
            return null;
    }
}

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