import React, { useState } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, useForm, router } from "@inertiajs/react";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle
} from "@/Components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/Components/ui/tabs";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { Button } from "@/Components/ui/button";
import {
    Coins,
    Package,
    RefreshCcw,
    Monitor,
    Bell,
    Save,
    Settings,
    Send
} from "lucide-react";
import { toast } from "sonner";

interface Setting {
    key: string;
    value: string;
    description: string;
}

interface PageProps {
    settings: Record<string, Setting[]>;
}

export default function SettingIndex({ settings }: PageProps) {
    const [isTesting, setIsTesting] = useState(false);
    const { data, setData, post, processing } = useForm({
        settings: Object.values(settings).flat().map(s => ({
            key: s.key,
            value: s.value
        }))
    });

    const [activeTab, setActiveTab] = useState("finance");

    const handleValueChange = (key: string, value: string) => {
        const newSettings = data.settings.map(s =>
            s.key === key ? { ...s, value } : s
        );
        setData('settings', newSettings);
    };

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('settings.update'), {
            onSuccess: () => toast.success("系統設定已更新"),
        });
    };

    const handleTestNotification = () => {
        setIsTesting(true);
        router.post(route('settings.test-notification'), { settings: data.settings }, {
            preserveScroll: true,
            onFinish: () => setIsTesting(false)
        });
    };

    const renderSettingRow = (setting: Setting) => {
        const currentVal = data.settings.find(s => s.key === setting.key)?.value || '';

        return (
            <div key={setting.key} className="grid grid-cols-1 md:grid-cols-2 gap-4 items-center py-4 border-b last:border-0 border-gray-100">
                <div>
                    <Label className="text-base font-semibold text-grey-0">{setting.description}</Label>
                    <p className="text-sm text-gray-500 mt-1">{setting.key}</p>
                </div>
                <div>
                    <Input
                        type={setting.key.includes('password') ? 'password' : 'text'}
                        value={currentVal}
                        onChange={(e) => handleValueChange(setting.key, e.target.value)}
                        className="max-w-xs"
                    />
                    {setting.key === 'notification.utility_fee_recipient_emails' && (
                        <p className="text-xs text-gray-400 mt-1 mt-2">請以半形逗點「,」分隔多個 Email，例如：a@test.com,b@test.com</p>
                    )}
                </div>
            </div>
        );
    };

    return (
        <AuthenticatedLayout
            breadcrumbs={[
                { label: "系統管理", href: "#" },
                { label: "系統設定" }
            ]}
        >
            <Head title="系統設定" />

            <div className="container mx-auto p-6 max-w-7xl">
                <div className="mb-6">
                    <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                        <Settings className="h-6 w-6 text-primary-main" />
                        系統設定
                    </h1>
                    <p className="text-gray-500 mt-2">
                        管理全系統的預設值與業務規則。
                    </p>
                </div>

                <form onSubmit={submit}>
                    <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
                        <TabsList className="bg-white border p-1 h-auto gap-2">
                            <TabsTrigger value="finance" className="gap-2 py-2 data-[state=active]:button-filled-primary data-[state=active]:text-white">
                                <Coins className="h-4 w-4" /> 財務設定
                            </TabsTrigger>
                            <TabsTrigger value="inventory" className="gap-2 py-2 data-[state=active]:button-filled-primary data-[state=active]:text-white">
                                <Package className="h-4 w-4" /> 庫存管理
                            </TabsTrigger>
                            <TabsTrigger value="turnover" className="gap-2 py-2 data-[state=active]:button-filled-primary data-[state=active]:text-white">
                                <RefreshCcw className="h-4 w-4" /> 周轉率分析
                            </TabsTrigger>
                            <TabsTrigger value="display" className="gap-2 py-2 data-[state=active]:button-filled-primary data-[state=active]:text-white">
                                <Monitor className="h-4 w-4" /> 顯示設定
                            </TabsTrigger>
                            <TabsTrigger value="notification" className="gap-2 py-2 data-[state=active]:button-filled-primary data-[state=active]:text-white">
                                <Bell className="h-4 w-4" /> 通知設定
                            </TabsTrigger>
                        </TabsList>

                        <TabsContent value="finance">
                            <Card>
                                <CardHeader>
                                    <CardTitle>財務設定</CardTitle>
                                    <CardDescription>管理應付帳款與稅務相關的預設規則。</CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-1">
                                    {settings.finance?.map(renderSettingRow)}
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="inventory">
                            <Card>
                                <CardHeader>
                                    <CardTitle>庫存管理</CardTitle>
                                    <CardDescription>管理商品效期、預警等庫存核心設定。</CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-1">
                                    {settings.inventory?.map(renderSettingRow)}
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="turnover">
                            <Card>
                                <CardHeader>
                                    <CardTitle>周轉率分析</CardTitle>
                                    <CardDescription>調整商品周轉率計算與滯銷判定的天數標準。</CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-1">
                                    {settings.turnover?.map(renderSettingRow)}
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="display">
                            <Card>
                                <CardHeader>
                                    <CardTitle>顯示設定</CardTitle>
                                    <CardDescription>設定全系統清單頁面的顯示偏好。</CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-1">
                                    {settings.display?.map(renderSettingRow)}
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <TabsContent value="notification">
                            <Card>
                                <CardHeader>
                                    <CardTitle>通知設定</CardTitle>
                                    <CardDescription>管理系統發送 Email 提醒信函（如：公共事業費逾期通知）的寄件帳號與預設收件群組。</CardDescription>
                                </CardHeader>
                                <CardContent className="space-y-1">
                                    {settings.notification?.map(renderSettingRow)}
                                </CardContent>
                            </Card>
                        </TabsContent>

                        <div className="flex justify-end gap-4 mt-6">
                            {activeTab === 'notification' && (
                                <Button
                                    type="button"
                                    variant="outline"
                                    className="button-outlined-primary"
                                    onClick={handleTestNotification}
                                    disabled={isTesting || processing}
                                >
                                    <Send className="h-4 w-4 mr-2" />
                                    {isTesting ? "發送中..." : "發送測試信"}
                                </Button>
                            )}
                            <Button
                                type="submit"
                                className="button-filled-primary"
                                disabled={processing}
                            >
                                <Save className="h-4 w-4 mr-2" />
                                {processing ? "儲存中..." : "儲存設定"}
                            </Button>
                        </div>
                    </Tabs>
                </form>
            </div>
        </AuthenticatedLayout>
    );
}

