import { Head, useForm } from '@inertiajs/react';
import { MessageSquare, Settings } from 'lucide-react';
import SystemAdminController from '@/actions/App/Http/Controllers/SystemAdminController';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useI18n } from '@/hooks/use-i18n';

type InstitutionData = {
    id: number;
    name_bn: string;
    name_en: string | null;
    settings?: {
        default_locale: string;
        invoice_print_locale: string;
        whatsapp_locale: string;
        invoice_due_day: number;
        whatsapp_enabled: boolean;
    } | null;
};

type LogRow = {
    id: number;
    channel: string;
    recipient_phone: string;
    message_body: string;
    status: string;
    sent_at: string | null;
};

export default function SystemSettings({
    institution,
    logs,
}: {
    institution: InstitutionData;
    logs: LogRow[];
}) {
    const { locale, t, localized } = useI18n();

    const settingsForm = useForm({
        default_locale: institution.settings?.default_locale ?? 'bn',
        invoice_print_locale: institution.settings?.invoice_print_locale ?? 'bilingual',
        whatsapp_locale: institution.settings?.whatsapp_locale ?? 'bn',
        invoice_due_day: institution.settings?.invoice_due_day ?? 10,
        whatsapp_enabled: institution.settings?.whatsapp_enabled ?? true,
    });

    const tplForm = useForm({
        event_key: 'payment_received',
        locale: 'bn',
        body_template: 'আসসালামু আলাইকুম, আপনার পেমেন্ট গৃহীত হয়েছে।',
    });

    return (
        <>
            <Head title={t('nav.settings', 'Institution Settings')} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">
                        {t('nav.settings', 'Institution Settings')} — {localized(institution, 'name')}
                    </h1>
                </div>

                <div className="grid gap-6 lg:grid-cols-2">
                    <div className="minimal-card p-6">
                        <div className="mb-4 flex items-center gap-2">
                            <Settings className="h-5 w-5 text-primary" />
                            <h2 className="font-semibold">{locale === 'bn' ? 'সাধারণ সেটিংস' : 'General Settings'}</h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                settingsForm.submit(SystemAdminController.updateSettings());
                            }}
                            className="space-y-4"
                        >
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'ডিফল্ট ভাষা' : 'Default Locale'}</Label>
                                <select
                                    value={settingsForm.data.default_locale}
                                    onChange={(e) => settingsForm.setData('default_locale', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                >
                                    <option value="bn">বাংলা (bn)</option>
                                    <option value="en">English (en)</option>
                                </select>
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'ইনভয়েস প্রিন্ট ভাষা' : 'Invoice Print Locale'}</Label>
                                    <select
                                        value={settingsForm.data.invoice_print_locale}
                                        onChange={(e) => settingsForm.setData('invoice_print_locale', e.target.value)}
                                        className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                    >
                                        <option value="bilingual">Bilingual (BN + EN)</option>
                                        <option value="bn">বাংলা (bn)</option>
                                        <option value="en">English (en)</option>
                                    </select>
                                </div>
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'হোয়াটসঅ্যাপ ভাষা' : 'WhatsApp Locale'}</Label>
                                    <select
                                        value={settingsForm.data.whatsapp_locale}
                                        onChange={(e) => settingsForm.setData('whatsapp_locale', e.target.value)}
                                        className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                    >
                                        <option value="bn">বাংলা (bn)</option>
                                        <option value="en">English (en)</option>
                                    </select>
                                </div>
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'মাসিক ইনভয়েস শেষ তারিখ (দিন)' : 'Invoice Due Day'}</Label>
                                <Input
                                    type="number"
                                    min={1}
                                    max={28}
                                    value={settingsForm.data.invoice_due_day}
                                    onChange={(e) => settingsForm.setData('invoice_due_day', Number(e.target.value))}
                                />
                            </div>
                            <label className="flex items-center gap-2 text-sm">
                                <input
                                    type="checkbox"
                                    checked={settingsForm.data.whatsapp_enabled}
                                    onChange={(e) => settingsForm.setData('whatsapp_enabled', e.target.checked)}
                                    className="h-4 w-4 accent-primary"
                                />
                                <span>{locale === 'bn' ? 'হোয়াটসঅ্যাপ নোটিফিকেশন সক্রিয়' : 'WhatsApp Notifications Enabled'}</span>
                            </label>
                            <Button type="submit" disabled={settingsForm.processing}>
                                {locale === 'bn' ? 'সেটিংস সংরক্ষণ' : 'Save Settings'}
                            </Button>
                        </form>
                    </div>

                    <div className="minimal-card p-6">
                        <div className="mb-4 flex items-center gap-2">
                            <MessageSquare className="h-5 w-5 text-primary" />
                            <h2 className="font-semibold">{locale === 'bn' ? 'হোয়াটসঅ্যাপ টেমপ্লেট' : 'WhatsApp Template'}</h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                tplForm.submit(SystemAdminController.storeTemplate());
                            }}
                            className="space-y-3"
                        >
                            <div className="grid grid-cols-2 gap-3">
                                <Input value={tplForm.data.event_key} onChange={(e) => tplForm.setData('event_key', e.target.value)} />
                                <select
                                    value={tplForm.data.locale}
                                    onChange={(e) => tplForm.setData('locale', e.target.value)}
                                    className="h-9 rounded-md border border-input bg-background px-2.5 text-sm"
                                >
                                    <option value="bn">bn</option>
                                    <option value="en">en</option>
                                </select>
                            </div>
                            <textarea
                                value={tplForm.data.body_template}
                                onChange={(e) => tplForm.setData('body_template', e.target.value)}
                                rows={3}
                                className="w-full rounded-md border border-input bg-background p-2.5 text-sm"
                            />
                            <Button type="submit" disabled={tplForm.processing}>
                                {locale === 'bn' ? 'টেমপ্লেট সংরক্ষণ' : 'Save Template'}
                            </Button>
                        </form>
                    </div>
                </div>

                <div className="minimal-card p-6">
                    <h2 className="mb-3 font-semibold">{locale === 'bn' ? 'সাম্প্রতিক হোয়াটসঅ্যাপ লগ' : 'Recent Notification Logs'}</h2>
                    <div className="space-y-2">
                        {logs.length === 0 ? (
                            <p className="text-sm text-muted-foreground">{locale === 'bn' ? 'কোনো লগ নেই।' : 'No logs yet.'}</p>
                        ) : (
                            logs.map((log) => (
                                <div key={log.id} className="rounded-lg border px-3 py-2 text-sm">
                                    <div className="flex justify-between text-xs text-muted-foreground">
                                        <span>{log.recipient_phone}</span>
                                        <span className="uppercase font-semibold text-emerald-600">{log.status}</span>
                                    </div>
                                    <p className="mt-1">{log.message_body}</p>
                                </div>
                            ))
                        )}
                    </div>
                </div>
            </div>
        </>
    );
}
