"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, ModuleIcon, EditIcon, DeleteIcon } from "@/components/icons";
import {
  MasterModule,
  getMasterModules,
  createMasterModule,
  updateMasterModule,
  deleteMasterModule,
} from "@/service/menu-modules";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import Swal from "sweetalert2";
import { FormField } from "@/components/form/common/FormField";

export default function ModulesSettingsPage() {
  const [modules, setModules] = useState<MasterModule[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingModule, setEditingModule] = useState<MasterModule | null>(null);
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    pathUrl: "",
    actionType: "",
    statusId: 1,
  });

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

  const loadData = async () => {
    setIsLoading(true);
    try {
      const res = await getMasterModules({ limit: 100 });
      if (!res?.error) {
        setModules(res?.data?.data || []);
      }
    } catch (error) {
      console.error("Error loading modules:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleOpenDialog = (module?: MasterModule) => {
    if (module) {
      setEditingModule(module);
      setFormData({
        name: module.name,
        description: module.description,
        pathUrl: module.pathUrl,
        actionType: module.actionType,
        statusId: module.statusId,
      });
    } else {
      setEditingModule(null);
      setFormData({
        name: "",
        description: "",
        pathUrl: "",
        actionType: "",
        statusId: 1,
      });
    }
    setIsDialogOpen(true);
  };

  const handleSave = async () => {
    try {
      if (editingModule) {
        const res = await updateMasterModule(editingModule.id, formData);
        if (res?.error) {
          Swal.fire({
            title: "Error",
            text: res?.message || "Failed to update module",
            icon: "error",
            confirmButtonText: "OK",
            customClass: {
              popup: 'swal-z-index-9999'
            }
          });
        } else {
          Swal.fire({
            title: "Success",
            text: "Module updated successfully",
            icon: "success",
            confirmButtonText: "OK",
            customClass: {
              popup: 'swal-z-index-9999'
            }
          });
          await loadData();
          setIsDialogOpen(false);
        }
      } else {
        const res = await createMasterModule(formData);
        if (res?.error) {
          Swal.fire({
            title: "Error",
            text: res?.message || "Failed to create module",
            icon: "error",
            confirmButtonText: "OK",
            customClass: {
              popup: 'swal-z-index-9999'
            }
          });
        } else {
          Swal.fire({
            title: "Success",
            text: "Module created successfully",
            icon: "success",
            confirmButtonText: "OK",
            customClass: {
              popup: 'swal-z-index-9999'
            }
          });
          await loadData();
          setIsDialogOpen(false);
        }
      }
    } catch (error) {
      console.error("Error saving module:", error);
      Swal.fire({
        title: "Error",
        text: "An unexpected error occurred",
        icon: "error",
        confirmButtonText: "OK",
        customClass: {
          popup: 'swal-z-index-9999'
        }
      });
    }
  };

  const handleDelete = async (module: MasterModule) => {
    const result = await Swal.fire({
      title: "Delete Module?",
      text: `Are you sure you want to delete "${module.name}"? This action cannot be undone.`,
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "Yes, delete it",
      cancelButtonText: "Cancel",
      customClass: {
        popup: 'swal-z-index-9999'
      }
    });

    if (result.isConfirmed) {
      try {
        const res = await deleteMasterModule(module.id);
        if (res?.error) {
          Swal.fire({
            title: "Error",
            text: res?.message || "Failed to delete module",
            icon: "error",
            confirmButtonText: "OK",
            customClass: {
              popup: 'swal-z-index-9999'
            }
          });
        } else {
          Swal.fire({
            title: "Deleted!",
            text: "Module has been deleted.",
            icon: "success",
            confirmButtonText: "OK",
            customClass: {
              popup: 'swal-z-index-9999'
            }
          });
          await loadData();
        }
      } catch (error) {
        console.error("Error deleting module:", error);
        Swal.fire({
          title: "Error",
          text: "An unexpected error occurred",
          icon: "error",
          confirmButtonText: "OK",
          customClass: {
            popup: 'swal-z-index-9999'
          }
        });
      }
    }
  };

  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">Modules Settings</h1>
            <p className="text-gray-600 mt-2">
              Manage system modules and their configurations
            </p>
          </div>
          <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
            <DialogTrigger asChild>
              <Button className="flex items-center gap-2" onClick={() => handleOpenDialog()}>
                <PlusIcon className="h-4 w-4" />
                Create Module
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle>
                  {editingModule ? `Edit Module: ${editingModule.name}` : "Create New Module"}
                </DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <FormField
                  label="Module Name"
                  name="name"
                  type="text"
                  placeholder="e.g., View Articles, Create Content"
                  value={formData.name}
                  onChange={(value) => setFormData({ ...formData, name: value })}
                  required
                />
                <FormField
                  label="Description"
                  name="description"
                  type="text"
                  placeholder="Brief description of the module"
                  value={formData.description}
                  onChange={(value) => setFormData({ ...formData, description: value })}
                  required
                />
                <FormField
                  label="Path URL"
                  name="pathUrl"
                  type="text"
                  placeholder="e.g., /api/articles, /api/content"
                  value={formData.pathUrl}
                  onChange={(value) => setFormData({ ...formData, pathUrl: value })}
                  required
                />
                <FormField
                  label="Action Type"
                  name="actionType"
                  type="select"
                  placeholder="Select action type"
                  value={formData.actionType}
                  onChange={(value) => setFormData({ ...formData, actionType: value })}
                  options={[
                    { value: "view", label: "View" },
                    { value: "create", label: "Create" },
                    { value: "update", label: "Update" },
                    { value: "delete", label: "Delete" },
                    { value: "approve", label: "Approve" },
                    { value: "reject", label: "Reject" },
                  ]}
                  required
                />
                <FormField
                  label="Status ID"
                  name="statusId"
                  type="number"
                  placeholder="1"
                  value={formData.statusId}
                  onChange={(value) => setFormData({ ...formData, statusId: Number(value) || 1 })}
                  required
                />
                <div className="flex items-center justify-end gap-2 pt-4 border-t">
                  <Button
                    variant="outline"
                    onClick={() => setIsDialogOpen(false)}
                  >
                    Cancel
                  </Button>
                  <Button onClick={handleSave}>
                    {editingModule ? "Update" : "Create"} Module
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>

        {isLoading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-4 text-gray-600">Loading modules...</p>
          </div>
        ) : modules.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {modules.map((module) => (
              <Card key={module.id} className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <CardTitle className="flex items-center justify-between">
                    <span className="truncate">{module.name}</span>
                    {module.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>
                    )}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2 mb-4">
                    <div className="text-sm text-gray-600">{module.description}</div>
                    <div className="text-xs text-gray-500 font-mono bg-gray-50 p-2 rounded">
                      {module.pathUrl}
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
                        {module.actionType}
                      </span>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleOpenDialog(module)}
                    >
                      <EditIcon className="h-4 w-4 mr-2" />
                      Edit
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1 text-red-600 hover:text-red-700 hover:bg-red-50"
                      onClick={() => handleDelete(module)}
                    >
                      <DeleteIcon className="h-4 w-4 mr-2" />
                      Delete
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <Card>
            <CardContent className="flex items-center justify-center py-12">
              <div className="text-center">
                <ModuleIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">No Modules Found</h3>
                <p className="text-gray-500 mb-4">
                  Create your first module to define system capabilities
                </p>
                <Button onClick={() => handleOpenDialog()}>
                  <PlusIcon className="h-4 w-4 mr-2" />
                  Create Module
                </Button>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </>
  );
}

