"use client";

import { useForm } from "react-hook-form";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import UsersSelect from "./UsersSelect";
import { UseCreateNotification } from "../hooks/UseCreateNotification";
import { toast } from "sonner";

type NotificationFormData = {
    title: string;
    message: string;
    target_type_id: number;
    user_ids?: number[];
};

type NotificationFormValues = {
    title: string;
    message: string;
    target_type_id: string;
    user_ids: number[]; 
};

export default function Notifications() {
    const form = useForm<NotificationFormValues>({
        defaultValues: {
            title: "",
            message: "",
            target_type_id: "2", // Default to "Send to ALL Users"
            user_ids: [],
        },
    });
    const { mutate, isPending } = UseCreateNotification();
    const { watch, handleSubmit } = form;
    const targetTypeId = watch("target_type_id");

    const onSubmit = (data: NotificationFormValues) => {

        const payload: NotificationFormData = {
            title: data.title,
            message: data.message,
            target_type_id: Number(data.target_type_id),
            user_ids: data.target_type_id === "1" ? data.user_ids : undefined,
        };
        mutate(payload, {
            onSuccess: () => {
                toast.success("Notification created successfully", {
                    position : "top-right",
                });
                form.reset();
            },
            onError: (error) => {
                toast.error("Failed to create notification");
            },
        });

    };

    return (
        <Card className="max-w-2xl mx-auto my-6">
            <CardHeader>
                <CardTitle>Send Notification</CardTitle>
            </CardHeader>
            <CardContent>
                <Form {...form}>
                    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="title"
                            rules={{ required: "Title is required" }}
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Title</FormLabel>
                                    <FormControl>
                                        <Input placeholder="e.g., Welcome" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="message"
                            rules={{ required: "Message is required" }}
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Message</FormLabel>
                                    <FormControl>
                                        <Textarea
                                            placeholder="e.g., Welcome to Sanad platform"
                                            className="min-h-[100px]"
                                            {...field}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="target_type_id"
                            rules={{ required: "Target type is required" }}
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Send To</FormLabel>
                                    <Select
                                        onValueChange={field.onChange}
                                        defaultValue={field.value}
                                    >
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder="Select target" />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            <SelectItem value="1">Send to Selected Users</SelectItem>
                                            <SelectItem value="2">Send to ALL Users</SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        {targetTypeId === "1" && (
                            <FormField
                                control={form.control}
                                name="user_ids"
                                rules={{
                                    validate: (value) => {
                                        if (targetTypeId === "1" && (!value || value.length === 0)) {
                                            return "Please select at least one user";
                                        }
                                        return true;
                                    },
                                }}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Select Users</FormLabel>
                                        <FormControl>
                                            <UsersSelect
                                                value={field.value}
                                                onChange={field.onChange}
                                                placeholder="Select users to notify..."
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        )}
                        <div className="pt-4">
                            <Button type="submit">Send Notification</Button>
                        </div>
                    </form>
                </Form>
            </CardContent>
        </Card>
    );
}