"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";

import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import axios from "axios";

import { motion } from "framer-motion";

import { MessageCircle, Send } from "lucide-react";

import clsx from "clsx";

import PostgrestError, { ANIMATION_EASE } from "@/lib/config";
import { cn, formatDate } from "@/lib/utils";
import { createClient } from "@/utils/supabase/client";
import { Tables } from "@/utils/supabase/database.types";

import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Button, buttonVariants } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";

import Spinner from "@/components/spinner";
import { Card } from "@/components/ui/card";

import { editAgentSchema } from "../schemas/edit-agent-schema";
import Link from "next/link";
import { toast } from "sonner";

type EditAgentCardProps = {
  agentId: string;
  disabled?: boolean;
};

export function EditAgentCard({
  agentId,
  disabled = false,
}: EditAgentCardProps) {
  const {
    data: agentsData,
    isLoading,
    error,
  } = useQuery({
    retry: 0,
    queryKey: ["agents", agentId],
    queryFn: async ({ signal }) => {
      const supabase = createClient();

      const response = await supabase
        .from("agents")
        .select("*")
        .eq("id", parseInt(agentId))
        .limit(1)
        .single();

      if (response.error) throw new PostgrestError(response.error);

      return response;
    },
  });

  if (error) return <p className="text-center">{error.message}</p>;

  if (isLoading || !agentsData || !agentsData.data)
    return <Spinner className="mx-auto" />;

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{
        duration: 0.8,
        ease: ANIMATION_EASE,
      }}
    >
      <CardContent agent={agentsData.data} disabled={disabled} />
    </motion.div>
  );
}

const CardContent = ({
  agent,
  disabled,
}: {
  agent: Tables<"agents">;
  disabled: boolean;
}) => {
  const { id, image_url, name, model_type, description, user_id } = agent;

  const router = useRouter();

  const form = useForm<z.infer<typeof editAgentSchema>>({
    resolver: zodResolver(editAgentSchema),
    defaultValues: {
      userId: user_id,
      name: name,
      description: description,
      modelType: model_type,
    },
    mode: "onChange",
  });

  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: async (values: z.infer<typeof editAgentSchema>) => {
      const supabase = createClient();

      const { data, error } = await supabase
        .from("agents")
        .update({
          name: values.name,
          description: values.description,
        })
        .eq("id", id)
        .select()
        .single();
      if (error) throw new PostgrestError(error);

      return data;
    },
    onSuccess: (data: Tables<"agents">) => {
      console.log(data);
      toast.success("Data has successfully updated");
      queryClient.invalidateQueries({
        queryKey: ["agents", id],
      });
    },
  });

  const onSubmit = (values: z.infer<typeof editAgentSchema>) => {
    mutation.mutate(values);
  };

  const {
    formState: { errors },
  } = form;

  if (mutation.isSuccess)
    return (
      <CompleteComponent
        agentId={mutation.data.id.toString()}
        agentName={mutation.data.name}
      />
    );

  return (
    <Card className="p-6 bg-transparent">
      <div className="flex flex-col sm:flex-row justify-between gap-3 mb-4">
        <figure className="relative h-[275px] min-w-full sm:h-[215px] sm:min-w-[275px] rounded-xl overflow-hidden">
          <Image
            src={image_url}
            fill={true}
            alt="test"
            className="object-cover"
          />
        </figure>
        <div className="grow sm:ml-auto">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Agent Name</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="astrobot"
                        className={cn(
                          errors.name && "focus-visible:ring-destructive"
                        )}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Description</FormLabel>
                    <FormControl>
                      <Textarea
                        rows={4}
                        placeholder="For answering daily questions."
                        className={cn(
                          errors.description && "focus-visible:ring-destructive"
                        )}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div>
                <div className="flex justify-end gap-4">
                  <Button
                    variant="outline"
                    disabled={mutation.isPending}
                    onClick={() => router.back()}
                    type="button"
                  >
                    {mutation.isPending && <Spinner className="h-4 w-4 mr-2" />}
                    Back
                  </Button>
                  <Button type="submit" disabled={mutation.isPending}>
                    {mutation.isPending && <Spinner className="h-4 w-4 mr-2" />}
                    Submit
                  </Button>
                </div>
              </div>
            </form>
          </Form>
        </div>
      </div>
    </Card>
  );
};

const CompleteComponent = ({
  agentId,
  agentName,
}: {
  agentId: string;
  agentName: string;
}) => {
  return (
    <>
      <div className="flex flex-col justify-center items-center  py-4">
        <div className="h-20 w-20 flex flex-col justify-center items-center rounded-full bg-primary">
          <svg
            width="61"
            height="41"
            viewBox="0 0 61 41"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <rect
              x="0.5"
              y="14.6426"
              width="5.85703"
              height="4.39277"
              fill="white"
            />
            <rect
              x="6.35693"
              y="19.0342"
              width="7.32129"
              height="8.78555"
              fill="white"
            />
            <rect
              x="13.6787"
              y="27.8223"
              width="5.85703"
              height="4.39277"
              fill="white"
            />
            <rect
              x="19.5354"
              y="32.2148"
              width="7.32129"
              height="8.78555"
              fill="white"
            />
            <rect
              x="26.8567"
              y="27.8223"
              width="5.85703"
              height="4.39277"
              fill="white"
            />
            <rect
              x="32.7136"
              y="19.0342"
              width="8.78555"
              height="8.78555"
              fill="white"
            />
            <rect
              x="41.4993"
              y="14.6426"
              width="5.85703"
              height="4.39277"
              fill="white"
            />
            <rect
              x="47.3562"
              y="5.85645"
              width="8.78555"
              height="8.78555"
              fill="white"
            />
            <rect x="56.1418" width="4.39277" height="5.85703" fill="white" />
          </svg>
        </div>
        <h3 className="text-xl py-4 font-bold">Agent succesfully created!</h3>
        <p className="text-lg text-muted-foreground mb-3">
          You can try to have a conversation with your agent.
        </p>
        <Link
          href={`/agents/${agentId}`}
          target="blank"
          className={buttonVariants({ variant: "default" })}
        >
          <svg
            width="16"
            height="16"
            viewBox="0 0 17 18"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            className="mr-2"
          >
            <path
              d="M8.50006 0.875C7.0973 0.874694 5.71836 1.23757 4.49745 1.9283C3.27654 2.61904 2.25526 3.6141 1.53301 4.81664C0.810765 6.01918 0.412159 7.38822 0.375993 8.79052C0.339826 10.1928 0.66733 11.5806 1.32663 12.8188L0.439908 15.4789C0.366459 15.6992 0.355799 15.9355 0.409125 16.1615C0.462451 16.3874 0.577655 16.5941 0.741823 16.7582C0.905992 16.9224 1.11264 17.0376 1.3386 17.0909C1.56456 17.1443 1.80091 17.1336 2.02116 17.0602L4.68131 16.1734C5.77098 16.753 6.97836 17.0767 8.21181 17.12C9.44525 17.1633 10.6724 16.925 11.8 16.4232C12.9276 15.9215 13.926 15.1694 14.7196 14.2241C15.5132 13.2789 16.0809 12.1652 16.3799 10.9678C16.6788 9.77029 16.7009 8.52047 16.4447 7.31315C16.1885 6.10584 15.6605 4.97276 14.901 3.99993C14.1415 3.02711 13.1703 2.24009 12.0612 1.69864C10.9521 1.15718 9.73427 0.875506 8.50006 0.875ZM5.06256 9.9375C4.87714 9.9375 4.69589 9.88252 4.54172 9.7795C4.38755 9.67649 4.26739 9.53007 4.19643 9.35876C4.12547 9.18746 4.1069 8.99896 4.14308 8.8171C4.17925 8.63525 4.26854 8.4682 4.39965 8.33709C4.53076 8.20598 4.69781 8.11669 4.87967 8.08051C5.06152 8.04434 5.25002 8.06291 5.42133 8.13386C5.59264 8.20482 5.73905 8.32498 5.84207 8.47915C5.94508 8.63332 6.00006 8.81458 6.00006 9C6.00006 9.24864 5.90129 9.4871 5.72548 9.66291C5.54966 9.83873 5.31121 9.9375 5.06256 9.9375ZM8.50006 9.9375C8.31464 9.9375 8.13339 9.88252 7.97922 9.7795C7.82505 9.67649 7.70489 9.53007 7.63393 9.35876C7.56297 9.18746 7.5444 8.99896 7.58058 8.8171C7.61675 8.63525 7.70604 8.4682 7.83715 8.33709C7.96826 8.20598 8.13531 8.11669 8.31717 8.08051C8.49902 8.04434 8.68752 8.06291 8.85883 8.13386C9.03014 8.20482 9.17655 8.32498 9.27957 8.47915C9.38258 8.63332 9.43756 8.81458 9.43756 9C9.43756 9.24864 9.33879 9.4871 9.16298 9.66291C8.98716 9.83873 8.74871 9.9375 8.50006 9.9375ZM11.9376 9.9375C11.7521 9.9375 11.5709 9.88252 11.4167 9.7795C11.2625 9.67649 11.1424 9.53007 11.0714 9.35876C11.0005 9.18746 10.9819 8.99896 11.0181 8.8171C11.0543 8.63525 11.1435 8.4682 11.2747 8.33709C11.4058 8.20598 11.5728 8.11669 11.7547 8.08051C11.9365 8.04434 12.125 8.06291 12.2963 8.13386C12.4676 8.20482 12.6141 8.32498 12.7171 8.47915C12.8201 8.63332 12.8751 8.81458 12.8751 9C12.8751 9.24864 12.7763 9.4871 12.6005 9.66291C12.4247 9.83873 12.1862 9.9375 11.9376 9.9375Z"
              fill="white"
            />
          </svg>
          Chat with {agentName}
        </Link>
      </div>
      {/* form footer  */}
      <div>
        <div className="flex justify-end gap-4">
          <Link
            href="/agents"
            className={buttonVariants({ variant: "outline" })}
          >
            Back to agent list
          </Link>
        </div>
      </div>
    </>
  );
};
