"use client";

import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { toast } from "sonner";
import axios from "axios";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Circle, RefreshCw } from "lucide-react";

// Define form schema
const settingsFormSchema = z.object({
    telegramBotToken: z.string().optional(),
    pineconeIndexName: z.string().optional(),
    pineconeNamespace: z.string().optional(),
    pineconeHost: z.string().optional(), // Add this new field
});


type SettingsFormValues = z.infer<typeof settingsFormSchema>;

export default function SettingsPage() {
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [isRestarting, setIsRestarting] = useState<boolean>(false);

    // Initialize form
    const form = useForm<SettingsFormValues>({
        resolver: zodResolver(settingsFormSchema),
        defaultValues: {
            telegramBotToken: "",
            pineconeIndexName: "",
            pineconeNamespace: "",
            pineconeHost: "",
        },
    });

    // Fetch current settings
    useEffect(() => {
        const fetchSettings = async () => {
            try {
                setIsLoading(true);
                const response = await axios.get("/api/panel-setting");
                form.reset({
                    telegramBotToken: response.data.telegramBotToken || "",
                    pineconeIndexName: response.data.pineconeIndexName || "",
                    pineconeNamespace: response.data.pineconeNamespace || "",
                    pineconeHost: response.data.pineconeHost || "", // Add this line
                });
            } catch (error) {
                toast.error("بارگذاری تنظیمات با شکست مواجه شد");
                console.error(error);
            } finally {
                setIsLoading(false);
            }
        };

        fetchSettings();
    }, [form]);

    // Handle form submission
    const onSubmit = async (values: SettingsFormValues) => {
        try {
            setIsLoading(true);

            await axios.post("/api/panel-setting", values);

            toast.success("تنظیمات با موفقیت به‌روزرسانی شد");
        } catch (error) {
            toast.error("به‌روزرسانی تنظیمات با شکست مواجه شد");
            console.error(error);
        } finally {
            setIsLoading(false);
        }
    };

    // Handle bot restart
    const handleRestartBot = async () => {
        try {
            setIsRestarting(true);
            await axios.get("/api/telegram");
            toast.success("ربات با موفقیت راه‌اندازی مجدد شد");
        } catch (error: any) {
            let message = "راه‌اندازی مجدد ربات با شکست مواجه شد";
            if (axios.isAxiosError(error)) {
                if (error.response) {
                    message += `: ${error.response.data?.message || error.response.statusText}`;
                } else if (error.request) {
                    message += ": عدم دریافت پاسخ از سرور";
                } else if (error.message) {
                    message += `: ${error.message}`;
                }
            }
            toast.error(message);
            console.error(error);
        } finally {
            setIsRestarting(false);
        }
    };

    return (
        <div className="container mx-auto py-10">
            <div className="mb-8">
                <h1 className="text-3xl font-bold">تنظیمات</h1>
                <p className="text-muted-foreground">تنظیمات پنل خود را مدیریت کنید</p>
            </div>

            <Card>
                <CardHeader>
                    <CardTitle>پیکربندی ربات</CardTitle>
                    <CardDescription>
                        تنظیمات یکپارچه‌سازی ربات تلگرام خود را پیکربندی کنید
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
                            <FormField
                                control={form.control}
                                name="telegramBotToken"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>توکن ربات تلگرام</FormLabel>
                                        <FormControl>
                                            <Input dir="ltr" style={{ direction: "ltr" }}
                                                placeholder="توکن ربات تلگرام خود را وارد کنید"
                                                {...field}
                                            />
                                        </FormControl>
                                        <FormDescription>
                                            توکن ربات تلگرام شما که از طریق BotFather ایجاد شده است
                                        </FormDescription>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="pineconeIndexName"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>نام ایندکس Pinecone</FormLabel>
                                        <FormControl>
                                            <Input dir="ltr" style={{ direction: "ltr" }}
                                                placeholder="نام ایندکس Pinecone خود را وارد کنید"
                                                {...field}
                                            />
                                        </FormControl>
                                        <FormDescription>
                                            نام ایندکس Pinecone برای ذخیره و بازیابی وکتورهای متن
                                        </FormDescription>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="pineconeNamespace"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>فضای نام Pinecone</FormLabel>
                                        <FormControl>
                                            <Input dir="ltr" style={{ direction: "ltr" }}
                                                placeholder="فضای نام Pinecone خود را وارد کنید"
                                                {...field}
                                            />
                                        </FormControl>
                                        <FormDescription>
                                            فضای نام اختیاری برای جداسازی داده‌ها در ایندکس Pinecone
                                        </FormDescription>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="pineconeHost"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>میزبان Pinecone</FormLabel>
                                        <FormControl>
                                            <Input
                                                dir="ltr"
                                                style={{ direction: "ltr" }}
                                                placeholder="میزبان Pinecone خود را وارد کنید"
                                                {...field}
                                            />
                                        </FormControl>
                                        <FormDescription>
                                            آدرس میزبان Pinecone برای اتصال به API
                                        </FormDescription>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                            <div className="flex flex-row gap-4">
                                <Button type="submit" disabled={isLoading}>
                                    {isLoading && (
                                        <Circle className="mr-2 h-4 w-4 animate-spin" />
                                    )}
                                    ذخیره تغییرات
                                </Button>

                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={handleRestartBot}
                                    disabled={isRestarting}
                                >
                                    {isRestarting ? (
                                        <Circle className="mr-2 h-4 w-4 animate-spin" />
                                    ) : (
                                        <RefreshCw className="mr-2 h-4 w-4" />
                                    )}
                                    راه‌اندازی مجدد ربات
                                </Button>
                            </div>
                        </form>
                    </Form>
                </CardContent>
            </Card>
        </div>
    );
}