import React from 'react';
import { Head, useForm } from '@inertiajs/react';
import { toast } from 'sonner';
import AdminLayout from '@/cp/Layouts/AdminLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/Components/ui/card";
import { Label } from "@/Components/ui/label";
import { Button } from "@/Components/ui/button";
import { Switch } from "@/Components/ui/switch";
import { 
    Save, BellRing, Mail, Smartphone, Loader2, 
    PackageCheck, Truck, ShoppingBag, MessageSquareText, Bot 
} from "lucide-react"; 
import { useTranslation } from '@/hooks/useTranslation';

export default function Notifications({ settings }) {
    const { t } = useTranslation();
    const parseBool = (key, defaultVal) => settings[key] !== undefined ? settings[key] === '1' : defaultVal;

    const { data, setData, post, processing } = useForm({
        notify_forgot_password_email: parseBool('notify_forgot_password_email', true),
        notify_forgot_password_sms: parseBool('notify_forgot_password_sms', false),
        
        notify_order_placed_email: parseBool('notify_order_placed_email', true),
        notify_order_placed_sms: parseBool('notify_order_placed_sms', false),
        
        notify_order_shipped_email: parseBool('notify_order_shipped_email', true),
        notify_order_shipped_sms: parseBool('notify_order_shipped_sms', false),
        
        notify_order_completed_email: parseBool('notify_order_completed_email', false),
        notify_order_completed_sms: parseBool('notify_order_completed_sms', false),
        
        notify_new_message_email: parseBool('notify_new_message_email', true),
        
        // --- NEW STATE FOR AUTOMATED CHAT ---
        notify_order_status_chat: parseBool('notify_order_status_chat', true), 
    });

    const submit = (e) => {
        e.preventDefault();
        post(route('cp.settings.notifications.update'), {
            preserveScroll: true,
            onSuccess: () => toast.success(t('Notification settings saved successfully!')),
            onError: () => toast.error(t('Failed to save settings.'))
        });
    };

    const ToggleRow = ({ title, desc, emailKey, smsKey, icon: Icon }) => (
        <div className="border rounded-xl p-5 bg-background shadow-sm space-y-4">
            <div className="flex items-center gap-2">
                <Icon className="w-5 h-5 text-primary" />
                <div>
                    <h4 className="font-bold text-lg">{t(title)}</h4>
                    <p className="text-sm text-muted-foreground">{t(desc)}</p>
                </div>
            </div>
            
            <div className={`grid grid-cols-1 ${smsKey ? 'md:grid-cols-2' : ''} gap-4`}>
                {/* Email Toggle */}
                {emailKey && (
                    <div className="flex items-center justify-between p-4 border rounded-lg bg-blue-500/5 border-blue-500/20">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-blue-500/20 rounded-md">
                                <Mail className="w-4 h-4 text-blue-600" />
                            </div>
                            <div>
                                <Label className="font-bold text-blue-700 dark:text-blue-500">{t('Send Email')}</Label>
                            </div>
                        </div>
                        <Switch 
                            checked={data[emailKey]} 
                            onCheckedChange={(v) => setData(emailKey, v)}
                            className="data-[state=checked]:bg-blue-600"
                        />
                    </div>
                )}

                {/* SMS Toggle */}
                {smsKey && (
                    <div className="flex items-center justify-between p-4 border rounded-lg bg-green-500/5 border-green-500/20">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-green-500/20 rounded-md">
                                <Smartphone className="w-4 h-4 text-green-600" />
                            </div>
                            <div>
                                <Label className="font-bold text-green-700 dark:text-green-500">{t('Send SMS')}</Label>
                            </div>
                        </div>
                        <Switch 
                            checked={data[smsKey]} 
                            onCheckedChange={(v) => setData(smsKey, v)}
                            className="data-[state=checked]:bg-green-600"
                        />
                    </div>
                )}
            </div>
        </div>
    );

    return (
        <AdminLayout>
            <Head title={t('Notifications & Alerts')} />

            <div className="max-w-4xl mx-auto space-y-6 pb-10">
                <div className="flex items-center gap-3 mb-6">
                    <BellRing className="w-8 h-8 text-primary" />
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">{t('Notifications & Alerts')}</h2>
                        <p className="text-muted-foreground text-sm">{t('Manage which events trigger an Email, SMS or Chat message.')}</p>
                    </div>
                </div>

                <form onSubmit={submit}>
                    <Card className="shadow-sm border-border/50">
                        <CardHeader className="bg-muted/10 border-b pb-4">
                            <CardTitle>{t('System Triggers')}</CardTitle>
                            <CardDescription>{t('Activate or deactivate communication channels per module.')}</CardDescription>
                        </CardHeader>
                        
                        <CardContent className="p-6 space-y-6">

                            {/* --- NEW: Automated Chat Notification Toggle --- */}
                            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-5 border-2 rounded-xl bg-orange-500/5 border-orange-500/20">
                                <div className="flex items-start gap-3">
                                    <div className="p-2 bg-orange-500/20 rounded-md shrink-0">
                                        <Bot className="w-5 h-5 text-orange-600" />
                                    </div>
                                    <div>
                                        <Label className="font-bold text-lg text-orange-700 dark:text-orange-500">{t('Automated Order Chat Messages')}</Label>
                                        <p className="text-sm text-orange-600/80 dark:text-orange-400/80 mt-1">
                                            {t('Automatically send a direct chat message from the Seller to the Buyer whenever their order status changes (Placed, Shipped, Cancelled, Refunded, etc).')}
                                        </p>
                                    </div>
                                </div>
                                <Switch 
                                    checked={data.notify_order_status_chat} 
                                    onCheckedChange={(v) => setData('notify_order_status_chat', v)}
                                    className="data-[state=checked]:bg-orange-600 shrink-0"
                                />
                            </div>

                            <div className="h-px bg-border my-6"></div>
                            
                            <ToggleRow 
                                title="New Chat Message" 
                                desc="Sent to the recipient when they receive a new chat message."
                                emailKey="notify_new_message_email"
                                icon={MessageSquareText}
                            />
                            
                            <div className="h-px bg-border my-6"></div>

                            <ToggleRow 
                                title="Order Placed / Confirmed" 
                                desc="Sent to Buyer & Seller when an order is successfully created and paid."
                                emailKey="notify_order_placed_email"
                                smsKey="notify_order_placed_sms"
                                icon={ShoppingBag}
                            />

                            <ToggleRow 
                                title="Order Shipped" 
                                desc="Sent to Buyer when the Seller marks the order as Shipped and adds tracking info."
                                emailKey="notify_order_shipped_email"
                                smsKey="notify_order_shipped_sms"
                                icon={Truck}
                            />

                            <ToggleRow 
                                title="Order Completed" 
                                desc="Sent to Buyer & Seller when the Buyer confirms package receipt."
                                emailKey="notify_order_completed_email"
                                smsKey="notify_order_completed_sms"
                                icon={PackageCheck}
                            />

                            <div className="h-px bg-border my-6"></div>

                            <ToggleRow 
                                title="Password Reset (OTP)" 
                                desc="Sent when a user requests to reset their forgotten password."
                                emailKey="notify_forgot_password_email"
                                smsKey="notify_forgot_password_sms"
                                icon={BellRing}
                            />
                            
                        </CardContent>

                        <CardFooter className="bg-muted/10 border-t py-4 justify-end">
                            <Button type="submit" disabled={processing} className="min-w-[140px] shadow-sm">
                                {processing ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
                                {t('Save Preferences')}
                            </Button>
                        </CardFooter>
                    </Card>
                </form>
            </div>
        </AdminLayout>
    );
}