"use client";

import { z } from "zod";
import { useRef } from "react";
import { CustomImage } from "@/components/custom-image";
import { toast } from "sonner";
import { ArrowLeft, CopyIcon, ImageIcon } from "lucide-react";
import { useForm } from "react-hook-form";
import { useRouter } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";

import { cn } from "@/lib/utils";
import { useConfirm } from "@/hooks/use-confirm";
import { DottedSeparator } from "@/components/dotted-separator";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";

import { Workspace } from "../types";
import { updateWorkspaceSchema } from "../schemas";
import { useUpdateWorkspace } from "../api/use-update-workspace";
import { useDeleteWorkspace } from "../api/use-delete-workspace";
import { useResetInviteCode } from "../api/use-reset-invite-code";
import { AvailableUsersList } from "@/features/members/components/available-users-list";
import { useGetCurrentMember } from "@/features/members/api/use-get-current-member";
import { MemberRole } from "@/features/members/types";

interface EditWorkspaceFormProps {
  onCancel?: () => void;
  initialValues: Workspace;
}

export const EditWorkspaceForm = ({
  onCancel,
  initialValues,
}: EditWorkspaceFormProps) => {
  const router = useRouter();
  const { mutate, isPending } = useUpdateWorkspace();
  const { data: currentMember } = useGetCurrentMember({ workspaceId: initialValues.id });

  const { mutate: deleteWorkspace, isPending: isDeletingWorkspace } =
    useDeleteWorkspace();

  const { mutate: resetInviteCode, isPending: isResettingInviteCode } =
    useResetInviteCode();

  const [DeleteDialog, confirmDelete] = useConfirm(
    "Delete Workspace",
    "This action cannot be undone.",
    "destructive"
  );

  const inputRef = useRef<HTMLInputElement>(null);

  const form = useForm<z.infer<typeof updateWorkspaceSchema>>({
    resolver: zodResolver(updateWorkspaceSchema),
    defaultValues: {
      ...initialValues,
      image: initialValues.imageUrl ?? "",
    },
  });

  const fullInviteLink = `${window.location.origin}/workspaces/${initialValues.id}/join/${initialValues.inviteCode}`;

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      form.setValue("image", file);
    }
  };

  const onSubmit = (values: z.infer<typeof updateWorkspaceSchema>) => {
    const finalValues = {
      ...values,
      image: values.image instanceof File ? values.image : "",
    };
    mutate({ form: finalValues, param: { workspaceId: initialValues.id } });
  };

  const handleDelete = async () => {
    const ok = await confirmDelete();

    if (!ok) return;

    deleteWorkspace(
      {
        param: { workspaceId: initialValues.id },
      },
      {
        onSuccess: () => {
          window.location.href = "/";
        },
      }
    );
  };

  const handleResetInviteCode = () => {
    resetInviteCode({
      param: { workspaceId: initialValues.id },
    });
  };

  const handleCopyInviteLink = () => {
    navigator.clipboard
      .writeText(fullInviteLink)
      .then(() => toast.success("Invite link copied to clipboard"));
  };

  const isCurrentUserAdmin = currentMember?.role === MemberRole.ADMIN;

  return (
    <div className="flex flex-col gap-y-4">
      <DeleteDialog />
      <Card className="size-full border-none shadow-none">
        {/* <CardHeader className="flex flex-row items-center gap-x-4 p-7 space-y-0">
          <Button
            size="sm"
            variant="secondary"
            onClick={
              onCancel
                ? onCancel
                : () => router.push(`/workspaces/${initialValues.id}`)
            }
          >
            <ArrowLeft className="size-4 mr-2" />
            Back
          </Button>
          <CardTitle className="text-xl font-bold">
            {initialValues.name}
          </CardTitle>
        </CardHeader> */}
        {/* <div className="px-7">
          <DottedSeparator />
        </div> */}
        <CardContent className="p-7 pt-0">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)}>
              <div className="flex flex-col gap-y-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Workspace name</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          placeholder="Enter workspace name"
                          autoComplete="off"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="image"
                  render={({ field }) => (
                    <div className="flex flex-col gap-y-2">
                      <div className="flex items-center gap-x-5">
                        {field.value ? (
                          <div className="size-[72px] relative rounded-md overflow-hidden">
                            <CustomImage
                              src={
                                field.value instanceof File
                                  ? URL.createObjectURL(field.value)
                                  : field.value
                              }
                              alt="Workspace"
                              className="object-cover"
                              fill
                              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                            />
                          </div>
                        ) : (
                          <Avatar className="size-[72px]">
                            <AvatarFallback>
                              <ImageIcon className="size-[36px] text-neutral-400" />
                            </AvatarFallback>
                          </Avatar>
                        )}
                        <div className="flex flex-col">
                          <p className="text-sm">Workspace icon</p>
                          <p className="text-xs text-muted-foreground">
                            JPG, JPEG, PNG, SVG or WEBP, max 1mb
                          </p>
                          <input
                            hidden
                            type="file"
                            ref={inputRef}
                            disabled={isPending}
                            onChange={handleImageChange}
                            accept=".jpg, .jpeg, .png, .svg, .webp"
                            autoComplete="off"
                          />
                          {field.value ? (
                            <Button
                              size="xs"
                              type="button"
                              variant="destructive"
                              className="w-fit mt-2"
                              disabled={isPending}
                              onClick={() => {
                                field.onChange(null);
                                if (inputRef.current)
                                  inputRef.current.value = "";
                              }}
                            >
                              Remove image
                            </Button>
                          ) : (
                            <Button
                              size="xs"
                              type="button"
                              variant="tertiary"
                              className="w-fit mt-2"
                              disabled={isPending}
                              onClick={() => inputRef.current?.click()}
                            >
                              Upload image
                            </Button>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                />
              </div>
              <DottedSeparator className="py-7" />
              <div className="flex items-center justify-between">
                <Button
                  type="button"
                  size="lg"
                  variant="outline"
                  onClick={onCancel}
                  disabled={isPending}
                  className={cn(!onCancel && "invisible")}
                >
                  Cancel
                </Button>
                <Button
                  disabled={isPending}
                  type="submit"
                  className="w-fit ml-auto"
                >
                  Save changes
                </Button>
              </div>
            </form>
          </Form>
        </CardContent>
      </Card>

      {/* Only show member management for admins */}
      {isCurrentUserAdmin && (
        <Card className="size-full border-none shadow-none">
          <CardContent className="p-7">
            <div className="flex flex-col">
              <div className="flex items-center gap-2">
                <h3 className="font-bold">Members</h3>
              </div>
              <p className="text-sm text-muted-foreground">
                Add users to your workspace or use the invite link. Use the Members tab to view and manage all members.
              </p>

              {/* Available Users List */}
              <AvailableUsersList workspaceId={initialValues.id} />

              <DottedSeparator className="my-4" />

              <h4 className="text-sm font-medium mb-2">Invite Link</h4>
              <div className="flex items-center gap-x-2">
                <Input name="inviteLink" value={fullInviteLink} readOnly />
                <Button
                  onClick={handleCopyInviteLink}
                  variant="outline"
                  className="size-12"
                >
                  <CopyIcon className="size-5" />
                </Button>
              </div>
              <DottedSeparator className="py-7" />
              <Button
                type="button"
                className="w-fit ml-auto"
                size="sm"
                variant="tertiary"
                disabled={isPending || isResettingInviteCode}
                onClick={handleResetInviteCode}
              >
                Reset invite link
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Only show danger zone for admins */}
      {isCurrentUserAdmin && (
        <Card className="size-full border-none shadow-none">
          <CardContent className="p-7">
            <div className="flex flex-col">
              <h3 className="font-bold text-red-600">Danger Zone!</h3>
              <p className="text-sm text-muted-foreground">
                Deleting a workspace is irreversible and will remove all
                associated data
              </p>
              <DottedSeparator className="py-7" />
              <Button
                type="button"
                size="sm"
                variant="destructive"
                disabled={isPending || isDeletingWorkspace}
                onClick={handleDelete}
                className="w-fit ml-auto"
              >
                Delete workspace
              </Button>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
};
