"use client";

import React, { useState, useRef, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { PlusCircle } from "lucide-react";
import SubcategoryCard from "./subcategoryCard";
import {
  useUpdateReligionSettings,
  useUpdateRelationshipSettings,
} from "@/src/utils/hooks/useGetAdminSettings";
import LoadingSpinner from "../../reusables/ui/LoadingSpinner";
import { toast } from "react-toastify";
import ConfirmationPopover from "../../reusables/ui/adminActionPopup";

interface SettingsPopupPropTypes {
  reference: "relationship" | "religion" | "";
  isOpen: boolean;
  onClose: () => void;
  data: {
    id: number;
    key: string;
    value: any;
    created_at: string;
    updated_at: string;
  };
}

interface ItemType {
  id?: number;
  name: string;
  subcategories?: string[];
}

interface ConfirmationState {
  isOpen: boolean;
  type: "edit" | "delete" | null;
  itemId: number | null;
  itemName: string;
}

export default function Popup({
  reference,
  isOpen,
  onClose,
  data,
}: SettingsPopupPropTypes) {
  const [itemName, setItemName] = useState("");
  const [subcategories, setSubcategories] = useState<string[]>([]);
  const [subcategoryInputValue, setSubcategoryInputValue] = useState("");
  const [items, setItems] = useState<ItemType[]>([]);
  const [isEditing, setIsEditing] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const subcategoryInput = useRef<null | HTMLInputElement>(null);

  // Confirmation state
  const [confirmation, setConfirmation] = useState<ConfirmationState>({
    isOpen: false,
    type: null,
    itemId: null,
    itemName: "",
  });

  const popupRef = useRef<HTMLDivElement>(null);

  // Mutation hooks
  const updateReligionMutation = useUpdateReligionSettings();
  const updateRelationshipMutation = useUpdateRelationshipSettings();

  // Transform data to items format based on reference type
  useEffect(() => {
    if (data && data.value) {
      if (reference === "relationship") {
        const relationshipItems = Array.isArray(data.value)
          ? data.value.map((item, index) => ({
              id: index + 1,
              name: item,
            }))
          : [];
        setItems(relationshipItems);
      } else if (reference === "religion") {
        const religionItems =
          data.value &&
          typeof data.value === "object" &&
          !Array.isArray(data.value)
            ? Object.entries(data.value).map(([name, details], index) => ({
                id: index + 1,
                name,
                subcategories: (details as any)?.denominations || [],
              }))
            : [];
        setItems(religionItems);
      }
    } else {
      setItems([]);
    }
  }, [data, reference]);

  // Handle click outside to close
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        popupRef.current &&
        !popupRef.current.contains(event.target as Node)
      ) {
        onClose();
      }
    }

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen, onClose]);

  // Reset form when popup closes
  useEffect(() => {
    if (!isOpen) {
      setItemName("");
      setSubcategories([]);
      setSubcategoryInputValue("");
      setIsEditing(false);
      setEditingId(null);
      setDeletingId(null);
      // Reset confirmation state
      setConfirmation({
        isOpen: false,
        type: null,
        itemId: null,
        itemName: "",
      });
    }
  }, [isOpen]);

  // Add subcategory to religion
  const handleAddSubcategory = () => {
    const value = subcategoryInputValue.trim();
    if (value && !subcategories.includes(value)) {
      setSubcategories([...subcategories, value]);
      setSubcategoryInputValue("");
    }
  };

  // Remove subcategory
  const handleRemoveSubcategory = (subcategory: string) => {
    setSubcategories(subcategories.filter((item) => item !== subcategory));
  };

  // Open edit confirmation
  const confirmEdit = (id: number) => {
    const item = items.find((item) => item.id === id);
    if (!item) return;

    if (item.name === "Marriage") {
      toast.info("Default items cannot be edited");
      return;
    }

    setConfirmation({
      isOpen: true,
      type: "edit",
      itemId: id,
      itemName: item.name,
    });
  };

  // Open delete confirmation
  const confirmDelete = (id: number) => {
    const item = items.find((item) => item.id === id);
    if (!item) return;

    if (item.name === "Marriage") {
      toast.info("Default items cannot be deleted");
      return;
    }

    setConfirmation({
      isOpen: true,
      type: "delete",
      itemId: id,
      itemName: item.name,
    });
  };

  // Close confirmation
  const closeConfirmation = () => {
    setConfirmation({
      isOpen: false,
      type: null,
      itemId: null,
      itemName: "",
    });
  };

  // Handle confirmation
  const handleConfirmAction = () => {
    if (confirmation.type === "edit" && confirmation.itemId !== null) {
      handleEdit(confirmation.itemId);
      closeConfirmation();
    } else if (confirmation.type === "delete" && confirmation.itemId !== null) {
      handleDelete(confirmation.itemId);
      closeConfirmation();
    }
  };

  // Edit item
  const handleEdit = (id: number) => {
    const item = items.find((item) => item.id === id);
    if (item) {
      setItemName(item.name);
      if (item.subcategories) {
        setSubcategories(item.subcategories);
      }
      setIsEditing(true);
      setEditingId(id);
    }
  };

  // Delete item
  const handleDelete = async (id: number) => {
    const item = items.find((item) => item.id === id);
    if (!item) return;

    setDeletingId(id);

    try {
      if (reference === "relationship") {
        const updatedValues = items
          .filter((i) => i.id !== id)
          .map((i) => i.name);

        await updateRelationshipMutation.mutateAsync(updatedValues);
        toast.success("Relationship type deleted successfully");
      } else if (reference === "religion") {
        const updatedValues = { ...data.value };
        delete updatedValues[item.name];

        await updateReligionMutation.mutateAsync(updatedValues);
        toast.success("Religion deleted successfully");
      }

      setItems(items.filter((item) => item.id !== id));
    } catch (error) {
      toast.error("Failed to delete item");
      console.error("Delete error:", error);
    } finally {
      setDeletingId(null);
    }
  };

  // Add new item or update existing one
  const handleAddItem = async () => {
    if (!itemName.trim()) {
      toast.error("Please enter a name");
      return;
    }

    try {
      if (reference === "religion") {
        // For religion, we only validate subcategories when editing
        // if (isEditing && subcategories.length === 0) {
        //   toast.error("Please add at least one denomination");
        //   return;
        // }

        const updatedValues = { ...data.value };

        if (isEditing && editingId !== null) {
          // Update existing religion item
          const oldItem = items.find((item) => item.id === editingId);
          if (oldItem) {
            delete updatedValues[oldItem.name];
          }
        }

        // Add/update the religion with its denominations
        updatedValues[itemName] = {
          denominations: subcategories,
        };

        await updateReligionMutation.mutateAsync(updatedValues);
        toast.success(
          isEditing
            ? "Religion updated successfully"
            : "Religion added successfully"
        );
      } else {
        // For relationship
        let updatedValues: string[];

        if (isEditing && editingId !== null) {
          // Update existing relationship item
          updatedValues = items.map((item) =>
            item.id === editingId ? itemName : item.name
          );
        } else {
          // Create new relationship item
          updatedValues = [...items.map((item) => item.name), itemName];
        }

        await updateRelationshipMutation.mutateAsync(updatedValues);
        toast.success(
          isEditing
            ? "Relationship type updated successfully"
            : "Relationship type added successfully"
        );
      }

      onClose();
    } catch (error) {
      toast.error("Failed to save changes");
      console.error("Save error:", error);
    }
  };

  if (!isOpen) return null;

  const isLoading =
    updateReligionMutation.isPending || updateRelationshipMutation.isPending;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div
        ref={popupRef}
        className={`bg-white rounded-lg shadow-lg w-full ${
          reference === "religion" ? "md:max-w-xl max-w-md" : "max-w-md"
        }`}
      >
        <div className="p-6">
          <h2 className="text-lg font-semibold mb-4">
            {reference === "relationship"
              ? "Create and Update relationship types"
              : "Create and Update Religion types"}
          </h2>

          <div className="mb-6">
            <div className="flex flex-col md:flex-row gap-2 mb-2">
              <div className="flex-1">
                <label className="block text-xs mb-1 font-semibold">
                  {reference === "relationship"
                    ? "Relationship name"
                    : "Religion name"}
                </label>
                <Input
                  type="text"
                  value={itemName}
                  onChange={(e) => setItemName(e.target.value)}
                  className="w-full"
                  disabled={
                    itemName.toLowerCase() === "christianity" ||
                    itemName.toLowerCase() === "islam"
                  }
                />
              </div>

              {reference === "religion" && (
                <div className="flex-1">
                  <label className="block mb-1 font-semibold text-xs">
                    Add sub category
                  </label>
                  <div className="flex justify-end items-end">
                    <Input
                      type="text"
                      className="w-full"
                      ref={subcategoryInput}
                      value={subcategoryInputValue}
                      onChange={(e) => setSubcategoryInputValue(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          e.preventDefault();
                          handleAddSubcategory();
                        }
                      }}
                    />
                    <Button
                      variant="ghost"
                      className={`rounded px-2 hover:bg-transparent ${
                        !subcategoryInputValue.trim()
                          ? "cursor-not-allowed"
                          : "cursor-pointer"
                      }`}
                      onClick={handleAddSubcategory}
                      disabled={!subcategoryInputValue.trim()}
                    >
                      <PlusCircle className="h-5 w-5 text-[#16166C]" />
                    </Button>
                  </div>
                </div>
              )}
            </div>

            {reference === "religion" && subcategories.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-2 max-h-[100px] z-10 overflow-y-auto">
                {subcategories.map((subcat, index) => (
                  <div key={index} className="">
                    <SubcategoryCard
                      subcategory={subcat}
                      remove={() => handleRemoveSubcategory(subcat)}
                    />
                  </div>
                ))}
              </div>
            )}

            <Button
              onClick={handleAddItem}
              className="bg-[#16166C] hover:bg-[#16166C]/90 text-white cursor-pointer mt-2"
              disabled={isLoading}
            >
              {isLoading && !deletingId && <LoadingSpinner />}
              {isEditing ? "Update" : "Add"}
            </Button>
          </div>

          {/* Table Structure */}
          <div className="rounded-md">
            <table className="min-w-full divide-y-0">
              <thead className="divide-y-0">
                <tr>
                  <th
                    scope="col"
                    className="px-4 py-2 text-left text-xs font-medium text-black uppercase tracking-wider"
                  >
                    {reference === "relationship"
                      ? "Relationship types"
                      : "Religion types"}
                  </th>
                  {reference === "religion" && (
                    <th
                      scope="col"
                      className="px-4 py-2 text-left text-xs font-medium text-black uppercase tracking-wider"
                    >
                      Sub category
                    </th>
                  )}
                  <th
                    scope="col"
                    className="px-4 py-2 text-right text-xs font-medium text-black uppercase tracking-wider"
                  >
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="bg-[#16166C0A] divide-y divide-gray-[#00000066]">
                {items.map((item) => (
                  <tr key={item.id} className={`hover:bg-white`}>
                    <td className="px-4 py-3 whitespace-nowrap text-sm font-semibold">
                      {item.name}
                    </td>
                    {reference === "religion" && (
                      <td className="px-4 py-3 whitespace-nowrap">
                        <div className="flex flex-wrap gap-1 max-w-xs max-h-20 overflow-y-auto">
                          {item.subcategories?.map((subcat, idx) => (
                            <span
                              key={idx}
                              className="bg-[#00000080] text-white text-xs px-2 py-1 rounded-full"
                            >
                              {subcat}
                            </span>
                          ))}
                        </div>
                      </td>
                    )}
                    <td className="px-4 py-3 whitespace-nowrap text-right text-sm">
                      <div className="flex justify-end space-x-2 relative">
                        <Button
                          onClick={(e) => {
                            e.stopPropagation();
                            // confirmEdit(item.id!);
                            handleEdit(item.id!);
                          }}
                          className={`text-xs px-6 py-1 rounded-full cursor-pointer ${
                            item.name?.toLowerCase() === "marriage" ||
                            item.name?.toLowerCase() === "colleague" ||
                            item.name?.toLowerCase() === "friendship"
                              ? "bg-[#D9D9D9] text-white hover:text-white hover:bg-[#D9D9D9] cursor-not-allowed"
                              : "bg-[#BEC105] hover:bg-[#BEC105] text-white"
                          }`}
                          size="sm"
                          disabled={
                            isLoading ||
                            deletingId !== null ||
                            item.name?.toLowerCase() === "marriage" ||
                            item.name?.toLowerCase() === "colleague" ||
                            item.name?.toLowerCase() === "friendship"
                          }
                        >
                          Edit
                        </Button>
                        <Button
                          onClick={(e) => {
                            e.stopPropagation();
                            confirmDelete(item.id!);
                          }}
                          className={`text-xs px-6 py-1 rounded-full cursor-pointer ${
                            item.name?.toLowerCase() === "marriage" ||
                            item.name?.toLowerCase() === "colleague" ||
                            item.name?.toLowerCase() === "friendship" ||
                            item.name?.toLowerCase() === "islam" ||
                            item.name?.toLowerCase() === "christianity"
                              ? "bg-[#D9D9D9] text-white hover:text-white hover:bg-[#D9D9D9] cursor-not-allowed"
                              : "bg-[#C10510] hover:bg-[#C10510] text-white"
                          }`}
                          size="sm"
                          disabled={
                            item.name?.toLowerCase() === "marriage" ||
                            item.name?.toLowerCase() === "colleague" ||
                            item.name?.toLowerCase() === "friendship" ||
                            item.name?.toLowerCase() === "islam" ||
                            item.name?.toLowerCase() === "christianity" ||
                            (isLoading && deletingId !== item.id)
                          }
                        >
                          {deletingId === item.id ? (
                            <div className="flex items-center gap-2 justify-center">
                              <LoadingSpinner />
                              Deleting...
                            </div>
                          ) : (
                            "Delete"
                          )}
                        </Button>

                        {/* Show confirmation popover when item matches confirmation state */}
                        {confirmation.isOpen &&
                          confirmation.itemId === item.id && (
                            <ConfirmationPopover
                              isOpen={confirmation.isOpen}
                              onClose={closeConfirmation}
                              onConfirm={handleConfirmAction}
                              title={
                                confirmation.type === "delete"
                                  ? "Confirm Delete"
                                  : "Confirm Edit"
                              }
                              message={
                                confirmation.type === "delete"
                                  ? `Are you sure you want to delete "${item.name}"?`
                                  : `Are you sure you want to edit "${item.name}"?`
                              }
                              confirmText={
                                confirmation.type === "delete"
                                  ? "Delete"
                                  : "Edit"
                              }
                              cancelText="Cancel"
                              position={
                                items.findIndex((i) => i.id === item.id) < 2
                                  ? "bottom"
                                  : "top"
                              }
                              isLoading={isLoading}
                            />
                          )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
