"use client";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Calendar as CalendarIcon } from "lucide-react";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { Calendar } from "@/components/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import React, { ReactNode } from "react";
import { useParams } from "next/navigation";
import { useRouter } from "next/navigation";
import { Badge } from "./ui/badge";

export default function TaskInfo({
  row,
  children,
}: {
  row: any;
  children: ReactNode;
}) {
  const [date, setDate] = React.useState<Date | undefined>(
    row.due_date ? new Date(row.due_date) : undefined
  );
  const params = useParams();
  const router = useRouter();
  const [isSheetOpen, setIsSheetOpen] = React.useState(false);

  async function updateTask(info: any) {
    try {
      const req = {
        id: row.id,
        ...info,
      };
      const data = await fetch(
        `/w/${params.workspaceID}/p/${params.projectID}/tasks/mutate`,
        {
          method: "PUT",
          body: JSON.stringify(req),
        }
      );
    } catch (err) {
      console.error(err);
    }
  }

  async function fetchWorkspaceUsers() {
    try {
      const data = await fetch(`/w/${params.workspaceID}/user/fetch`);
      const res = await data.json();
      console.log("FETCH WORKSPACE USERS RES ===>", res);
    } catch (err) {
      console.error(err);
    }
  }

  // TODO: add a function that takes in the task id and user id and then assigns the user to the task using the /w/:workspaceID/p/:projectID/tasks/assign API route.
  async function assignUserToTask() {
    try {
      const data = await fetch(
        `/w/${params.workspaceID}/p/${params.projectID}/tasks/assign`,
        {
          method: "POST",
          body: JSON.stringify({
            task_id: row.id,
            user_id: 1,
          }),
        }
      );
      const res = await data.json();
      console.log("ASSIGN USER TO TASK RES ===>", res);
    } catch (err) {
      console.error(err);
    }
  }

  const handleDateChange = (newDate: Date | undefined) => {
    setDate(newDate); // Update the local state
    if (newDate) {
      updateTask({ due_date: newDate.toISOString() }); // Persist the change
    }
  };

  const handleSheetOpenChange = (open: boolean) => {
    setIsSheetOpen(open);

    // If the sheet is being closed, refresh the router
    if (!open) {
      router.refresh();
    }
  };

  return (
    <Sheet open={isSheetOpen} onOpenChange={handleSheetOpenChange}>
      <div className="flex space-x-2">
        {row.feature_id && (
          <Badge variant="outline">FEAT-{row.feature_id}</Badge>
        )}
        <SheetTrigger className="max-w-[500px] truncate font-medium">
          {row.name}
        </SheetTrigger>
      </div>
      <SheetContent className="w-[800px]">
        <SheetHeader>
          <SheetTitle>{row.name}</SheetTitle>
          <SheetDescription>{row.description}</SheetDescription>
        </SheetHeader>

        <div className="flex flex-col space-y-2 py-4">
          {/* <div className="flex flex-row space-x-24 items-center">
            <h5 className="font-medium text-muted-foreground text-sm">
              Assignee
            </h5>
            <div className="w-1/3">
              <Select onValueChange={handleUserSelect}>
                <SelectTrigger>
                  <SelectValue placeholder="Select a user" />
                </SelectTrigger>
                <SelectContent>
                  {users.map((user) => (
                    <SelectItem key={user.id} value={user.id}>
                      {user.email}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div> */}
          <div className="flex flex-row space-x-24 items-center">
            <h5 className="font-medium text-muted-foreground text-sm">
              Status
            </h5>
            <div className="w-1/3">
              <Select
                defaultValue={row.status}
                onValueChange={(value) => updateTask({ status: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="backlog">Backlog</SelectItem>
                  <SelectItem value="todo">Todo</SelectItem>
                  <SelectItem value="in_progress">In Progress</SelectItem>
                  <SelectItem value="done">Done</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="flex flex-row space-x-24 items-center">
            <h5 className="font-medium text-muted-foreground text-sm">
              Priority
            </h5>
            <div className="w-1/3">
              <Select
                defaultValue={row.priority}
                onValueChange={(value) => updateTask({ priority: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select priority" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="low">Low</SelectItem>
                  <SelectItem value="medium">Medium</SelectItem>
                  <SelectItem value="high">High</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="flex flex-row space-x-24 items-center">
            <h5 className="font-medium text-muted-foreground text-sm">
              Due Date
            </h5>
            <div className="w-1/3">
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant={"outline"}
                    className={cn(
                      "w-[280px] justify-start text-left font-normal",
                      !date && "text-muted-foreground"
                    )}
                  >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {date ? format(date, "PPP") : <span>Pick a date</span>}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0">
                  <Calendar
                    mode="single"
                    selected={date}
                    onSelect={handleDateChange}
                    initialFocus
                  />
                </PopoverContent>
              </Popover>
            </div>
          </div>
          {children}
        </div>
      </SheetContent>
    </Sheet>
  );
}
