import { useEffect, useState } from "react";
import { ActionButton } from "@/components/ui/action-button";
import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { toast } from "@/components/ui/use-toast";
import { api } from "@/lib/trpc";
import { zodResolver } from "@hookform/resolvers/zod";
import { TRPCClientError } from "@trpc/client";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Textarea } from "@/components/ui/textarea";
import { zMetricSchema } from "@lifetracker/shared/types/metrics";

type CreateMetricSchema = z.infer<typeof zMetricSchema>;

export default function AddMetricDialog({
    initialMetric = undefined,
    children,
}: {
    initialMetric?: CreateMetricSchema;
    children?: React.ReactNode;
}) {
    const apiUtils = api.useUtils();
    const [isOpen, onOpenChange] = useState(false);
    const form = useForm<CreateMetricSchema>({
        resolver: zodResolver(zMetricSchema),
        defaultValues: initialMetric
    });
    const handleSuccess = (message: string) => {
        toast({
            description: message,
        });
        apiUtils.metrics.list.invalidate();
        onOpenChange(false);
    };

    const handleError = (error: any, defaultMessage: string) => {
        if (error instanceof TRPCClientError) {
            toast({
                variant: "destructive",
                description: error.message,
            });
        } else {
            toast({
                variant: "destructive",
                description: defaultMessage,
            });
        }
    };

    const { mutate, isPending } = initialMetric
        ? api.metrics.update.useMutation({
            onSuccess: () => handleSuccess("Metric updated successfully"),
            onError: (error) => handleError(error, "Failed to update metric"),
        })
        : api.metrics.create.useMutation({
            onSuccess: () => handleSuccess("New metric created successfully"),
            onError: (error) => handleError(error, "Failed to create metric"),
        });
    useEffect(() => {
        if (!isOpen) {
            form.reset();
        }
    }, [isOpen, form]);

    return (
        <Dialog open={isOpen} onOpenChange={onOpenChange}>
            <DialogTrigger asChild>{children}</DialogTrigger>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Track a New Metric</DialogTitle>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit((val) => mutate(val))}>
                        <div className="flex w-full flex-col space-y-2">
                            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "10px" }}>
                                <FormField
                                    control={form.control}
                                    name="name"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormControl>
                                                <Input
                                                    type="text"
                                                    placeholder="Name"
                                                    {...field}
                                                    className="w-full rounded border p-2"
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                <FormField
                                    control={form.control}
                                    name="unit"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormControl>
                                                <Input
                                                    type="text"
                                                    placeholder="Unit"
                                                    {...field}
                                                    className="w-full rounded border p-2"
                                                    disabled={(form.watch("type") === "count")}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                {/* Select field with "timeseries" and "count" */}

                                <FormField
                                    control={form.control}
                                    name="type"
                                    render={({ field }) => (
                                        <FormItem>
                                            <Select onValueChange={field.onChange} defaultValue={field.value}>
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="Select a type of metric to track" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    <SelectItem value="timeseries">Timeseries</SelectItem>
                                                    <SelectItem value="count">Count</SelectItem>
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                            </div>
                            <FormField
                                control={form.control}
                                name="description"
                                render={({ field }) => (
                                    <FormItem>
                                        {/* <FormLabel>Description</FormLabel> */}
                                        <FormControl>
                                            <Textarea
                                                placeholder="Description"
                                                {...field}
                                                className="w-full rounded border p-2"
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <DialogFooter className="sm:justify-end">
                                <DialogClose asChild>
                                    <Button type="button" variant="secondary">
                                        Close
                                    </Button>
                                </DialogClose>
                                <ActionButton
                                    type="submit"
                                    loading={isPending}
                                    disabled={isPending}
                                >
                                    {initialMetric ? "Update" : "Create"}
                                </ActionButton>
                            </DialogFooter>
                        </div>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    );
}
