"use client";

import { Loader2, Pencil } from "lucide-react";
import { useContext, useState } from "react";
import { boolean } from "zod";
import { AuthUIContext } from "../../lib/auth-ui-provider";
import { cn } from "../../lib/utils";
import type { Organization } from "../../types/organization";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import { Button } from "../ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog";
import { Separator } from "../ui/separator";
import { Skeleton } from "../ui/skeleton";
import { CreateOrganizationModal } from "./create-organization-modal";

export type OrganizationProfileCardClassNames = {
  base?: string;
  header?: string;
  title?: string;
  description?: string;
  separator?: string;
  section?: string;
  sectionLabel?: string;
  sectionContent?: string;
  profileSection?: string;
  profileContent?: string;
  avatar?: string;
  avatarFallback?: string;
  organizationName?: string;
  editButton?: string;
  leaveSection?: string;
  leaveButton?: string;
  skeleton?: string;
};

export interface OrganizationProfileCardProps {
  className?: string;
  classNames?: OrganizationProfileCardClassNames;
  showUpdateOrg?: (() => boolean) | boolean;
  logoSize?: number;
  logoExtension?: string;
}

export function OrganizationProfileCard({
  className,
  classNames,
  logoSize,
  logoExtension,
  showUpdateOrg,
}: OrganizationProfileCardProps) {
  const { authClient, createOrganizationUrl, navigate, toast } =
    useContext(AuthUIContext);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [leaveDialogOpen, setLeaveDialogOpen] = useState(false);
  const [isLeaving, setIsLeaving] = useState(false);
  const { data: remainingOrganizations } = authClient.useListOrganizations();
  const { data: organization, isPending } = authClient.useActiveOrganization();

  const handleLeaveOrganization = async () => {
    try {
      setIsLeaving(true);
      await authClient.organization.leaveOrganization(
        {},
        {
          async onSuccess(context) {
            toast({
              message: `You have successfully left ${organization?.name || "the organization"}.`,
              variant: "default",
            });
            if (remainingOrganizations && remainingOrganizations.length > 0) {
              await authClient.organization.setActive({
                organizationId: remainingOrganizations[0].id,
              });
              return;
            }
            setLeaveDialogOpen(false);

            navigate(createOrganizationUrl || "/create-org");
          },
          onError(context) {
            toast({
              message:
                context?.error?.message ??
                "Failed to leave the organization. Please try again.",
              variant: "error",
            });
          },
        }
      );
      setIsLeaving(false);
    } catch (error) {
    } finally {
    }
  };

  const showUpdateButton =
    typeof showUpdateOrg === "boolean"
      ? showUpdateOrg
      : typeof showUpdateOrg === "function"
        ? showUpdateOrg()
        : true;

  return (
    <div className={cn("w-full", classNames?.base, className)}>
      {/* Header section */}
      <div className={cn("mb-6", classNames?.header)}>
        <h1 className={cn("text-2xl font-semibold", classNames?.title)}>
          Organization Profile
        </h1>
        <p
          className={cn(
            "text-muted-foreground text-sm",
            classNames?.description
          )}
        >
          Manage organization profile
        </p>
      </div>
      <Separator className={classNames?.separator} />

      {/* Organization profile section */}
      <div
        className={cn(
          "flex items-center justify-between py-6",
          classNames?.section,
          classNames?.profileSection
        )}
      >
        <span
          className={cn(
            "text-base text-muted-foreground min-w-[140px]",
            classNames?.sectionLabel
          )}
        >
          Organization profile
        </span>

        <div
          className={cn(
            "flex items-center gap-6",
            classNames?.sectionContent,
            classNames?.profileContent
          )}
        >
          <div className="flex items-center gap-3">
            {isPending ? (
              <>
                <Skeleton
                  className={cn("h-10 w-10 rounded-full", classNames?.skeleton)}
                />
                <Skeleton className={cn("h-5 w-32", classNames?.skeleton)} />
              </>
            ) : (
              <>
                <Avatar className={cn("h-10 w-10", classNames?.avatar)}>
                  <AvatarImage
                    src={organization?.logo || undefined}
                    alt={organization?.name || "Organization"}
                  />
                  <AvatarFallback
                    className={cn(
                      "bg-gray-200 text-gray-700",
                      classNames?.avatarFallback
                    )}
                  >
                    {organization?.name?.charAt(0).toUpperCase() || "O"}
                  </AvatarFallback>
                </Avatar>
                <span
                  className={cn(
                    "text-base font-medium text-gray-900",
                    classNames?.organizationName
                  )}
                >
                  {organization?.name || "Organization Name"}
                </span>
              </>
            )}
          </div>
        </div>

        {showUpdateButton && (
          <Button
            variant="ghost"
            onClick={() => setEditModalOpen(true)}
            disabled={isPending}
            className={cn("font-medium", classNames?.editButton)}
          >
            <Pencil className="h-4 w-4 ml-2" />
            Edit profile
          </Button>
        )}
      </div>
      <Separator className={classNames?.separator} />

      <div
        className={cn(
          "flex items-center justify-between py-6",
          classNames?.section,
          classNames?.leaveSection
        )}
      >
        <span
          className={cn(
            "text-base text-muted-foreground",
            classNames?.sectionLabel
          )}
        >
          Leave organization
        </span>

        <Button
          variant="ghost"
          className={cn(
            "text-red-600 hover:text-red-700 hover:bg-red-50 font-medium",
            classNames?.leaveButton
          )}
          onClick={() => setLeaveDialogOpen(true)}
          disabled={isPending || isLeaving}
        >
          Leave
        </Button>
      </div>

      <CreateOrganizationModal
        open={editModalOpen}
        onOpenChange={setEditModalOpen}
        logoSize={logoSize}
        logoExtension={logoExtension}
        organization={organization as Organization}
        mode={"update"}
        title={"Update Organization"}
        description={
          "Update existing organization to collaborate with your team."
        }
      />

      <Dialog open={leaveDialogOpen} onOpenChange={setLeaveDialogOpen}>
        <DialogContent
          className="sm:max-w-[425px]"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle>Leave Organization</DialogTitle>
            <DialogDescription>
              This will remove you from{" "}
              {organization?.name || "this organization"}. You will lose access
              to all projects and resources associated with it. Are you sure you
              want to continue?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              disabled={isLeaving}
              variant="outline"
              onClick={() => !isLeaving && setLeaveDialogOpen(false)}
            >
              Cancel
            </Button>
            <Button
              disabled={isLeaving}
              variant="destructive"
              onClick={handleLeaveOrganization}
            >
              {isLeaving ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Leaving...
                </>
              ) : (
                "Leave Organization"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
