import Link from "next/link";
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";
import { Icon, } from "@/components/ui/icon";
import { icons } from "lucide-react";
import { titleCase } from "title-case";
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: {
            type: "count",
            ...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]);

    const [icon, setIcon] = useState("FileQuestion");
    if (initialMetric?.icon) {
        useEffect(() => {
            searchIcons(initialMetric.icon);
        }, []);
    }


    const searchIcons = (query: string) => {
        const icon = Object.keys(icons).find((i) => i.toLowerCase() == (query.toLowerCase()));
        if (icon) {
            setIcon(icon);
        }
        else {
            setIcon("FileQuestion");
            return;
        }
    }

    return (
        <Dialog open={isOpen} onOpenChange={onOpenChange}>
            <DialogTrigger asChild>{children}</DialogTrigger>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {initialMetric
                            ? "Update " + initialMetric.name
                            : "New " + titleCase(form.watch('type')) + " 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="type"
                                    render={({ field }) => (
                                        <FormItem>
                                            <Select onValueChange={field.onChange} defaultValue={initialMetric?.type ?? "count"}>
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder="Select a type of metric to track" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    <SelectItem value="drug">Drug</SelectItem>
                                                    <SelectItem value="diet">Diet</SelectItem>
                                                    <SelectItem value="workout">Workout</SelectItem>
                                                    <SelectItem value="sex">Sex</SelectItem>
                                                    <SelectItem value="count">Count</SelectItem>
                                                    <SelectItem value="timeseries">Timeseries</SelectItem>
                                                </SelectContent>
                                            </Select>
                                            <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"
                                                />
                                            </FormControl>
                                            <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>
                                )}
                            /><div className="flex gap-4 items-center">
                                <Icon color="white" size={36}
                                    name={icon}
                                /><FormField control={form.control} name="icon" render={({ field }) => (
                                    <FormItem>
                                        <FormControl>
                                            <Input
                                                type="text"
                                                placeholder="Icon"
                                                {...field}
                                                className="w-full rounded border p-2"
                                                onChange={(e) => {
                                                    searchIcons(e.target.value);
                                                    form.setValue("icon", e.target.value);
                                                }
                                                }
                                                onBlur={() => {
                                                    if (form.getValues("icon") == "" && initialMetric?.icon) {
                                                        {
                                                            form.setValue("icon", initialMetric.icon);
                                                            searchIcons(initialMetric.icon);
                                                        }
                                                    }
                                                }}
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )} />
                                <Link href="https://lucide.dev/icons" target="_blank" className="text-blue-500">Browse icons</Link>
                            </div>
                            <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 >
    );
}
