"use client";
import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { PlusIcon, SettingsIcon, MenuIcon, ModuleIcon } from "@/components/icons";
import {
  MasterMenu,
  MasterModule,
  MenuModule,
  getMasterMenus,
  getMasterModules,
  getMenuModulesByMenuId,
  createMenuModulesBatch,
  deleteMenuModule,
} from "@/service/menu-modules";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import Swal from "sweetalert2";

export default function MenuSettingsPage() {
  const [menus, setMenus] = useState<MasterMenu[]>([]);
  const [modules, setModules] = useState<MasterModule[]>([]);
  const [selectedMenu, setSelectedMenu] = useState<MasterMenu | null>(null);
  const [menuModules, setMenuModules] = useState<MenuModule[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedModuleIds, setSelectedModuleIds] = useState<number[]>([]);

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    if (selectedMenu) {
      loadMenuModules(selectedMenu.id);
    }
  }, [selectedMenu]);

  const loadData = async () => {
    setIsLoading(true);
    try {
      const [menusRes, modulesRes] = await Promise.all([
        getMasterMenus({ limit: 100 }),
        getMasterModules({ limit: 100 }),
      ]);

      if (!menusRes?.error) {
        setMenus(menusRes?.data?.data || []);
      }
      if (!modulesRes?.error) {
        setModules(modulesRes?.data?.data || []);
      }
    } catch (error) {
      console.error("Error loading data:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const loadMenuModules = async (menuId: number) => {
    try {
      const res = await getMenuModulesByMenuId(menuId);
      if (!res?.error) {
        setMenuModules(res?.data?.data || []);
        setSelectedModuleIds((res?.data?.data || []).map((mm: MenuModule) => mm.moduleId));
      }
    } catch (error) {
      console.error("Error loading menu modules:", error);
    }
  };

  const handleSaveModules = async () => {
    if (!selectedMenu) return;

    try {
      // Delete existing menu modules
      for (const menuModule of menuModules) {
        await deleteMenuModule(menuModule.id);
      }

      // Create new menu modules in batch
      if (selectedModuleIds.length > 0) {
        const res = await createMenuModulesBatch({
          menuId: selectedMenu.id,
          moduleIds: selectedModuleIds,
        });

        if (res?.error) {
          Swal.fire({
            title: "Error",
            text: res?.message || "Failed to save modules",
            icon: "error",
            confirmButtonText: "OK",
            customClass: {
              popup: 'swal-z-index-9999'
            }
          });
        } else {
          Swal.fire({
            title: "Success",
            text: "Modules saved successfully",
            icon: "success",
            confirmButtonText: "OK",
            customClass: {
              popup: 'swal-z-index-9999'
            }
          });
          await loadMenuModules(selectedMenu.id);
          setIsDialogOpen(false);
        }
      }
    } catch (error) {
      console.error("Error saving modules:", error);
      Swal.fire({
        title: "Error",
        text: "An unexpected error occurred",
        icon: "error",
        confirmButtonText: "OK",
        customClass: {
          popup: 'swal-z-index-9999'
        }
      });
    }
  };

  const toggleModuleSelection = (moduleId: number) => {
    setSelectedModuleIds((prev) =>
      prev.includes(moduleId)
        ? prev.filter((id) => id !== moduleId)
        : [...prev, moduleId]
    );
  };

  return (
    <>
      <SiteBreadcrumb />
      <div className="container mx-auto p-6 space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Menu Settings</h1>
            <p className="text-gray-600 mt-2">
              Manage menu and module associations
            </p>
          </div>
          <MenuIcon className="h-6 w-6 text-gray-500" />
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Menu List */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <MenuIcon className="h-5 w-5" />
                Menus
              </CardTitle>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <div className="text-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
                </div>
              ) : menus.length > 0 ? (
                <div className="space-y-2">
                  {menus.map((menu) => (
                    <button
                      key={menu.id}
                      onClick={() => setSelectedMenu(menu)}
                      className={`w-full text-left p-3 rounded-lg border transition-colors ${
                        selectedMenu?.id === menu.id
                          ? "bg-blue-50 border-blue-500 text-blue-900"
                          : "bg-white border-gray-200 hover:bg-gray-50"
                      }`}
                    >
                      <div className="font-medium">{menu.name}</div>
                      <div className="text-sm text-gray-500">{menu.description}</div>
                    </button>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  No menus found
                </div>
              )}
            </CardContent>
          </Card>

          {/* Selected Menu Modules */}
          <Card className="lg:col-span-2">
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <ModuleIcon className="h-5 w-5" />
                  {selectedMenu ? `${selectedMenu.name} - Modules` : "Select a Menu"}
                </CardTitle>
                {selectedMenu && (
                  <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                    <DialogTrigger asChild>
                      <Button className="flex items-center gap-2">
                        <PlusIcon className="h-4 w-4" />
                        Manage Modules
                      </Button>
                    </DialogTrigger>
                    <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
                      <DialogHeader>
                        <DialogTitle>Manage Modules for {selectedMenu.name}</DialogTitle>
                      </DialogHeader>
                      <div className="space-y-4">
                        <div className="space-y-2">
                          {modules.map((module) => (
                            <label
                              key={module.id}
                              className="flex items-start gap-3 p-3 border rounded-lg hover:bg-gray-50 cursor-pointer"
                            >
                              <input
                                type="checkbox"
                                checked={selectedModuleIds.includes(module.id)}
                                onChange={() => toggleModuleSelection(module.id)}
                                className="mt-1"
                              />
                              <div className="flex-1">
                                <div className="font-medium">{module.name}</div>
                                <div className="text-sm text-gray-500">{module.description}</div>
                                <div className="text-xs text-gray-400 mt-1">
                                  {module.pathUrl} • {module.actionType}
                                </div>
                              </div>
                            </label>
                          ))}
                        </div>
                        <div className="flex items-center justify-end gap-2 pt-4 border-t">
                          <Button
                            variant="outline"
                            onClick={() => setIsDialogOpen(false)}
                          >
                            Cancel
                          </Button>
                          <Button onClick={handleSaveModules}>
                            Save Modules
                          </Button>
                        </div>
                      </div>
                    </DialogContent>
                  </Dialog>
                )}
              </div>
            </CardHeader>
            <CardContent>
              {selectedMenu ? (
                menuModules.length > 0 ? (
                  <div className="space-y-2">
                    {menuModules.map((menuModule) => (
                      <div
                        key={menuModule.id}
                        className="flex items-center justify-between p-3 border rounded-lg"
                      >
                        <div>
                          <div className="font-medium">
                            {menuModule.module?.name || `Module ${menuModule.moduleId}`}
                          </div>
                          <div className="text-sm text-gray-500">
                            {menuModule.module?.description || "No description"}
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          {menuModule.position && (
                            <span className="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
                              Position: {menuModule.position}
                            </span>
                          )}
                          {menuModule.isActive ? (
                            <span className="px-2 py-1 text-xs bg-green-100 text-green-800 rounded-full">
                              Active
                            </span>
                          ) : (
                            <span className="px-2 py-1 text-xs bg-gray-100 text-gray-800 rounded-full">
                              Inactive
                            </span>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-12 text-gray-500">
                    <ModuleIcon className="h-12 w-12 mx-auto mb-4 text-gray-400" />
                    <p>No modules assigned to this menu</p>
                    <Button
                      className="mt-4"
                      onClick={() => setIsDialogOpen(true)}
                    >
                      <PlusIcon className="h-4 w-4 mr-2" />
                      Add Modules
                    </Button>
                  </div>
                )
              ) : (
                <div className="text-center py-12 text-gray-500">
                  <MenuIcon className="h-12 w-12 mx-auto mb-4 text-gray-400" />
                  <p>Select a menu to view its modules</p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </>
  );
}

