import React from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, useForm } 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,
    Save,
    Settings
} 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 { data, setData, post, processing } = useForm({
        settings: Object.values(settings).flat().map(s => ({
            key: s.key,
            value: s.value
        }))
    });

    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 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="text"
                        value={currentVal}
                        onChange={(e) => handleValueChange(setting.key, e.target.value)}
                        className="max-w-xs"
                    />
                </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 defaultValue="finance" 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>
                        </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>

                        <div className="flex justify-end gap-4 mt-6">
                            <Button
                                type="submit"
                                className="button-filled-primary"
                                disabled={processing}
                            >
                                <Save className="h-4 w-4 mr-2" />
                                {processing ? "儲存中..." : "儲存設定"}
                            </Button>
                        </div>
                    </Tabs>
                </form>
            </div>
        </AuthenticatedLayout>
    );
}
