import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { DataManagement } from "@/components/settings/DataManagement";
import { GlobalSettings } from "@/components/settings/GlobalSettings";
import { ProductSettings } from "@/components/settings/ProductSettings";
import { VendorSettings } from "@/components/settings/VendorSettings";
import { TemplateManagement } from "@/components/settings/TemplateManagement";
import { UserManagement } from "@/components/settings/UserManagement";
import { PromptManagement } from "@/components/settings/PromptManagement";
import { ReusableImageManagement } from "@/components/settings/ReusableImageManagement";
import { AuditLog } from "@/components/settings/AuditLog";
import { motion } from 'framer-motion';
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Protected } from "@/components/auth/Protected";
import { useContext, useMemo } from "react";
import { AuthContext } from "@/contexts/AuthContext";
import { Separator } from "@/components/ui/separator";

// Define types for settings structure
interface SettingsTab {
  id: string;
  permission: string;
  label: string;
}

interface SettingsGroup {
  id: string;
  label: string;
  tabs: SettingsTab[];
}

// Define available settings tabs with their permission requirements and groups
const SETTINGS_GROUPS: SettingsGroup[] = [
  {
    id: "inventory",
    label: "Inventory Settings",
    tabs: [
      { id: "global-settings", permission: "settings:global", label: "Global Settings" },
      { id: "product-settings", permission: "settings:products", label: "Product Settings" },
      { id: "vendor-settings", permission: "settings:vendors", label: "Vendor Settings" },
    ]
  },
  {
    id: "content",
    label: "Content Management", 
    tabs: [
      { id: "templates", permission: "settings:templates", label: "Template Management" },
      { id: "ai-prompts", permission: "settings:prompt_management", label: "AI Prompts" },
      { id: "reusable-images", permission: "settings:library_management", label: "Reusable Images" },
    ]
  },
  {
    id: "system",
    label: "System",
    tabs: [
      { id: "user-management", permission: "settings:user_management", label: "User Management" },
      { id: "data-management", permission: "settings:data_management", label: "Data Management" },
      { id: "audit-log", permission: "settings:audit_log", label: "Audit Log" },
    ]
  }
];

// Flatten tabs for easier access
const SETTINGS_TABS = SETTINGS_GROUPS.flatMap(group => group.tabs);

export function Settings() {
  const { user } = useContext(AuthContext);

  // Determine the first tab the user has access to
  const defaultTab = useMemo(() => {
    // Admin users have access to all tabs
    if (user?.is_admin) {
      return SETTINGS_TABS[0].id;
    }
    
    // Find the first tab the user has permission to access
    const firstAccessibleTab = SETTINGS_TABS.find(tab => 
      user?.permissions?.includes(tab.permission)
    );
    
    // Return the ID of the first accessible tab, or first tab as fallback
    return firstAccessibleTab?.id || SETTINGS_TABS[0].id;
  }, [user]);

  // Check if user has access to any tab
  const hasAccessToAnyTab = useMemo(() => {
    if (user?.is_admin) return true;
    return SETTINGS_TABS.some(tab => user?.permissions?.includes(tab.permission));
  }, [user]);

  // If user doesn't have access to any tabs, show a helpful message
  if (!hasAccessToAnyTab) {
    return (
      <motion.div layout className="container mx-auto py-6">
        <div className="mb-6">
          <h1 className="text-3xl font-bold">Settings</h1>
        </div>
        <Alert>
          <AlertDescription>
            You don't have permission to access any settings. Please contact an administrator for assistance.
          </AlertDescription>
        </Alert>
      </motion.div>
    );
  }

  // Function to check if the user has access to any tab in a group
  const hasAccessToGroup = (group: SettingsGroup): boolean => {
    if (user?.is_admin) return true;
    return group.tabs.some(tab => user?.permissions?.includes(tab.permission));
  };

  return (
    <motion.div layout className="container mx-auto py-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold">Settings</h1>
      </div>

      <Tabs defaultValue={defaultTab} orientation="vertical" className="flex flex-row min-h-[500px]">
        <div className="w-60 border-r pr-8">
          <TabsList className="flex flex-col h-auto justify-start items-stretch p-0 bg-transparent">
            {SETTINGS_GROUPS.map((group) => (
              hasAccessToGroup(group) && (
                <div key={group.id} className="">
                  <h3 className="font-semibold text-sm px-3 py-2 bg-muted border text-foreground rounded-md mb-2">
                    {group.label}
                  </h3>
                  <div className="space-y-1 pl-1">
                    {group.tabs.map((tab) => (
                      <Protected key={tab.id} permission={tab.permission}>
                        <TabsTrigger 
                          value={tab.id}
                          className="w-full justify-start px-3 py-2 text-sm font-normal text-muted-foreground data-[state=active]:font-medium data-[state=active]:text-accent-foreground data-[state=active]:shadow-none rounded-md data-[state=active]:underline"
                        >
                          {tab.label}
                        </TabsTrigger>
                      </Protected>
                    ))}
                  </div>
                  {/* Only add separator if not the last group */}
                  {group.id !== SETTINGS_GROUPS[SETTINGS_GROUPS.length - 1].id && (
                    <Separator className="mt-4 mb-4 opacity-70" />
                  )}
                </div>
              )
            ))}
          </TabsList>
        </div>

        <div className="pl-8 w-full">
          <TabsContent value="data-management" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected 
              permission="settings:data_management" 
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access Data Management.
                  </AlertDescription>
                </Alert>
              }
            >
              <DataManagement />
            </Protected>
          </TabsContent>

          <TabsContent value="global-settings" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected 
              permission="settings:global" 
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access Global Settings.
                  </AlertDescription>
                </Alert>
              }
            >
              <GlobalSettings />
            </Protected>
          </TabsContent>

          <TabsContent value="product-settings" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected 
              permission="settings:products" 
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access Product Settings.
                  </AlertDescription>
                </Alert>
              }
            >
              <ProductSettings />
            </Protected>
          </TabsContent>

          <TabsContent value="vendor-settings" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected 
              permission="settings:vendors" 
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access Vendor Settings.
                  </AlertDescription>
                </Alert>
              }
            >
              <VendorSettings />
            </Protected>
          </TabsContent>

          <TabsContent value="templates" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected 
              permission="settings:templates" 
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access Template Management.
                  </AlertDescription>
                </Alert>
              }
            >
              <TemplateManagement />
            </Protected>
          </TabsContent>
          
          <TabsContent value="ai-prompts" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected 
              permission="settings:prompt_management" 
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access AI Prompts.
                  </AlertDescription>
                </Alert>
              }
            >
              <PromptManagement />
            </Protected>
          </TabsContent>
          
          <TabsContent value="reusable-images" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected 
              permission="settings:library_management" 
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access Reusable Images.
                  </AlertDescription>
                </Alert>
              }
            >
              <ReusableImageManagement />
            </Protected>
          </TabsContent>
          
          <TabsContent value="user-management" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected
              permission="settings:user_management"
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access User Management.
                  </AlertDescription>
                </Alert>
              }
            >
              <UserManagement />
            </Protected>
          </TabsContent>

          <TabsContent value="audit-log" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
            <Protected
              permission="settings:audit_log"
              fallback={
                <Alert>
                  <AlertDescription>
                    You don't have permission to access the Audit Log.
                  </AlertDescription>
                </Alert>
              }
            >
              <AuditLog />
            </Protected>
          </TabsContent>
        </div>
      </Tabs>
    </motion.div>
  );
}
