"use client"

import { Button } from "@/Components/UI/Button"
import { Input } from "@/Components/UI/Input"
import { Badge } from "@/Components/UI/Badge"
import { Switch } from "@/Components/UI/Switch"
import { Modal } from "@/Components/UI/Modal"
import { Label } from "@/Components/UI/Label"
import CreateWorkspaceModal from "@/Components/CreateWorkspaceModal"
import DeleteModal from "@/Components/DeleteModal"
import DataTable from "@/Components/DataTable"
import { Plus, ArrowLeftRight, Eye, Trash2 } from "lucide-react"
import { useState, useEffect } from "react"
import AppLayout from "@/Layouts/AppLayout"
import { router } from "@inertiajs/react"
import { route } from "ziggy-js"
import { useDeleteHandler } from '@/hooks/useDeleteHandler';
import { useToggleHandler } from '@/hooks/useToggleHandler';
import { useBulkHandler } from '@/hooks/useBulkHandler';
import { formatDate } from '@/Lib';
import useTranslate from "@/hooks/useTranslate";


export default function WorkspaceSettings({ workspaces, auth, site_settings }) {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isShowWorkspaceModalOpen, setIsShowWorkspaceModalOpen] = useState(false)
  const [workspaceToShow, setWorkspaceToShow] = useState(null)
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
  const [workspaceToDelete, setWorkspaceToDelete] = useState(null)
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const t = useTranslate();


  const [workspaceList, setWorkspaceList] = useState(workspaces.data || [])

  useEffect(() => {
    setWorkspaceList(workspaces.data || [])
  }, [workspaces]);

  const breadcrumbs = [
    { label: "Home", href: route("user.home") },
    { label: "Workspace Settings" },
  ]


  const currentPage = workspaces.current_page;
  const perPage = workspaces.per_page;



  const columns = [
    {
      key: "id",
      label: "No",
      className: "w-16",
      cellClassName: "font-medium",
      render: (_item, index) => {
        return (currentPage - 1) * perPage + index + 1;
      }

    },
    {
      key: "name",
      label: "Workspace Name",
      cellClassName: "font-medium",
      render: (workspace) => (
        <div className="flex items-center gap-2">
          {workspace.name}
          {workspace.id === auth?.user?.current_workspace_id && (
            <Badge className="bg-gradient-to-r from-primary to-secondary text-white">Current</Badge>
          )}
        </div>
      ),
    },
    {
      key: "status",
      label: "Status",
      render: (workspace) => (
        <Switch
          checked={workspace.status === '1'}
          onCheckedChange={() => handleToggleWorkspace(workspace.id)}
          className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-cyan-500"
        />
      ),
    },
    { key: "email", label: "Email", cellClassName: "text-gray-600" },
  ]

  const filterOptions = [
    {
      label: "Active",
      value: "1",
      filterFn: (item) => item.status === '1',
    },
    {
      label: "Inactive",
      value: "0",
      filterFn: (item) => item.status !== '1',
    },
  ]

  const actionMenuItems = [
    { key: "switch", label: "Switch", icon: ArrowLeftRight },
    { key: "show", label: "Show", icon: Eye },
    { key: "delete", label: "Delete", icon: Trash2 },
  ]

  const { handleToggle, isToggling } = useToggleHandler('user.workspace.status.update', (id, newStatus) => {
    setWorkspaceList((prev) =>
      prev.map((workspace) =>
        workspace.id === id ? { ...workspace, status: newStatus } : workspace,
      ),
    );
  });

  const handleToggleWorkspace = (workspaceId) => {
    const workspace = workspaceList.find((w) => w.id === workspaceId);
    if (workspace) {
      handleToggle(workspaceId, workspace.status);
    }
  };


  const handleShowWorkspace = (workspace) => {
    setWorkspaceToShow(workspace)
    setIsShowWorkspaceModalOpen(true)
  }

  const handleDeleteClick = (workspace) => {
    setWorkspaceToDelete(workspace)
    setIsDeleteModalOpen(true)
  }

  const { handleDelete, isDeleting } = useDeleteHandler('user.workspace.delete', (deletedId) => {
    setWorkspaceList((prev) => prev.filter((w) => w.id !== deletedId));
    setIsDeleteModalOpen(false);
    setWorkspaceToDelete(null);
  });

  const { handleBulkAction, isBulkProcessing } = useBulkHandler(
    "user.workspace.bulk",
    (action, ids, statusEnum) => {
      setWorkspaceList((prev) => {
        switch (action) {
          case "active":
            return prev.map((w) =>
              ids.includes(w.id) ? { ...w, status: statusEnum.Active } : w
            )
          case "inactive":
            return prev.map((w) =>
              ids.includes(w.id) ? { ...w, status: statusEnum.Inactive } : w
            )
          case "delete":
            return prev.filter((w) => !ids.includes(w.id))
          default:
            return prev
        }
      })
    }
  )


  const handleSearchChange = (value) => {
    setSearchQuery(value);

    router.get(
      route("user.workspace.settings"),
      {
        search: value,
        status: statusFilter !== "all" ? statusFilter : undefined,
        page: 1,
      },
      { preserveState: true, replace: true }
    );
  };


  const handleFilterChange = (value) => {
    setStatusFilter(value);

    router.get(
      route("user.workspace.settings"),
      {
        search: searchQuery,
        status: value !== "all" ? value : undefined,
        page: 1,
      },
      { preserveState: true, replace: true }
    );
  };

  const handleSwitchWorkspace = (workspaceId) => {
    router.post(route('user.workspace.switch'), { id: workspaceId })
  }



  const handleRowAction = (action, workspace) => {
    switch (action) {
      case "switch":
        handleSwitchWorkspace(workspace.id)
        break
      case "show":
        handleShowWorkspace(workspace);
        break
      case "delete":
        handleDeleteClick(workspace)
        break
    }
  }



  return (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="flex-1 p-6 overflow-auto bg-gray-50 dark:bg-black">
        {/* Header */}
        <div className="flex items-center justify-between flex-wrap gap-4 mb-6">
          <div className="space-y-1">
            <h1 className="text-2xl font-bold">{t("Workspace Setting")}</h1>
            <p className="text-gray-500">Manage your workspace here</p>
          </div>
          <Button
            onClick={() => setIsModalOpen(true)}
            className="bg-gradient-to-r from-primary to-secondary text-white hover:from-sky-600 hover:to-cyan-600"
          >
            <Plus className="w-4 h-4 mr-2" />
            Add Workspace
          </Button>
        </div>

        <DataTable
          data={workspaceList}
          columns={columns}
          propName="workspaces"
          searchFields={["name", "email"]}
          searchPlaceholder={t("Search by name or email")}
          filterOptions={filterOptions}
          actionMenuItems={actionMenuItems}
          onSearch={handleSearchChange}
          onFilterChange={handleFilterChange}
          onBulkActive={(ids) => handleBulkAction("active", ids)}
          onBulkInactive={(ids) => handleBulkAction("inactive", ids)}
          onBulkDelete={(ids) => handleBulkAction("delete", ids)}
          onRowAction={handleRowAction}
          paginationData={{ links: workspaces.links, currentPage: workspaces.current_page, lastPage: workspaces.last_page }} // Pass only necessary data
        />

        {/* Create Workspace Modal */}
        <CreateWorkspaceModal
          isOpen={isModalOpen}
          onClose={() => setIsModalOpen(false)}
        />

        {/* Show Workspace Modal */}
        <Modal
          isOpen={isShowWorkspaceModalOpen}
          onClose={() => setIsShowWorkspaceModalOpen(false)}
          title="Workspace Information"
          showSubmit={false}
        >
          <div className="space-y-4">
            {/* Workspace Name */}
            <div className="flex items-center gap-4">
              <div>
                <h2 className="text-lg font-semibold">{workspaceToShow?.name}</h2>
              </div>
            </div>

            {/* Workspace Details */}
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <p className="text-gray-500">Email</p>
                <p className="font-medium">{workspaceToShow?.email}</p>
              </div>

              <div>
                <p className="text-gray-500">Created</p>
                <p className="font-medium">
                  {formatDate(workspaceToShow?.created_at, site_settings.date_format)}
                </p>
              </div>
              <div>
                <p className="text-gray-500">Status</p>
                <span
                  className={`px-2 py-1 text-xs rounded-full ${workspaceToShow?.status === '1' ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
                    }`}
                >
                  {workspaceToShow?.status === '1' ? "Active" : "Inactive"}
                </span>
              </div>
              <div>
                <p className="text-gray-500">Default</p>
                <span
                  className={`px-2 py-1 text-xs rounded-full ${workspaceToShow?.is_defualt === '1' ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
                    }`}
                >
                  {workspaceToShow?.is_defualt === '1' ? "Yes" : "No"}
                </span>
              </div>
            </div>
          </div>

        </Modal>

        {/* Delete Modal */}
        <DeleteModal
          isOpen={isDeleteModalOpen}
          onClose={() => setIsDeleteModalOpen(false)}
          title="Delete this workspace?"
          description="Are you really sure you want to delete this workspace?"
          onConfirm={() => handleDelete(workspaceToDelete?.id)}
          isDeleting={isDeleting}
        />
      </div>
    </AppLayout>
  )
}