"use client";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Settings, Trash } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { use, useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { useToast } from "./ui/use-toast";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
export function WorkspaceSettings() {
  const params = useParams();
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [userEmails, setUserEmails] = useState([]);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const { toast } = useToast();

  // function that takes in email, checks if there is a user associated. if there is, get the user id and add it to the profile_workspace junction table.
  async function addUserToWorkspace() {
    try {
      const data = await fetch(`/w/${params.workspaceID}/user/add`, {
        method: "POST",
        body: JSON.stringify({
          email: email,
        }),
      });
      const res = await data.json();
      if (res.status === 200) {
        toast({
          variant: "default",
          title: "User added to workspace!",
          description: "The user was successfully added to the workspace.",
        });
      } else {
        toast({
          variant: "destructive",
          title: "Uh oh! Something went wrong.",
          description: res.error,
        });
      }
    } 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);
      setUserEmails(res.emails.map((email: any) => email.email));
    } catch (err) {
      console.error(err);
    }
  }

  useEffect(() => {
    if (isDialogOpen) {
      fetchWorkspaceUsers();
    }
  }, [isDialogOpen]); // Effect runs when isDialogOpen changes

  async function deleteWorkspace() {
    try {
      const data = await fetch(`/w/${params.workspaceID}/delete`, {
        method: "DELETE",
      });
      const res = await data.json();
      console.log("DELETE WORKSPACE RES ===>", res);
      router.refresh();
      router.push("/dashboard");
    } catch (err) {
      console.error(err);
    }
  }

  return (
    <Dialog onOpenChange={() => setIsDialogOpen(!isDialogOpen)}>
      <Button size="icon" variant="ghost" asChild>
        <DialogTrigger>
          <Settings size={20} strokeWidth={1} />
        </DialogTrigger>
      </Button>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Workspace Settings</DialogTitle>
        </DialogHeader>
        <Separator />
        <Card className="shadow-none border-none ">
          <CardHeader>
            <CardTitle>Add users to this workspace</CardTitle>
            <CardDescription>
              Users will have access to all projects in the workspace.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex space-x-2">
              <Input
                placeholder="example@company.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
              <Button onClick={addUserToWorkspace}>Add User</Button>
            </div>
            <Separator className="my-4" />
            <div className="space-y-4">
              <h4 className="text-sm font-medium">People with access</h4>
              {userEmails.map((email: string) => (
                <div key={email} className="grid gap-6">
                  <div className="flex items-center justify-between space-x-4">
                    <div className="flex items-center space-x-4">
                      <Avatar>
                        <AvatarImage src="/avatars/03.png" />
                        <AvatarFallback>
                          {email.slice(0, 2).toUpperCase()}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <p className="text-sm font-medium leading-none">
                          {email}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <Separator className="my-4" />
            <Dialog>
              <Button variant="destructive" className="w-full" asChild>
                <DialogTrigger>
                  <Trash size={16} className="mr-2" />
                  Delete Workspace
                </DialogTrigger>
              </Button>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Are you sure?</DialogTitle>
                </DialogHeader>
                <DialogDescription>
                  <p>This action cannot be undone.</p>
                </DialogDescription>
                <Separator />
                <div className="flex flex-row justify-end">
                  <Button variant="destructive" onClick={deleteWorkspace}>
                    Delete
                  </Button>
                </div>
              </DialogContent>
            </Dialog>
          </CardContent>
        </Card>
      </DialogContent>
    </Dialog>
  );
}
