import React from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { SettingsLayout } from './components/SettingsLayout';
import { SettingsCard } from './components/SettingsCard';
import { SchemaForm, FormSchema } from '@/components/forms/SchemaForm';
import { useModuleSettings } from '@/hooks/useModuleSettings';
import { Button } from '@/components/ui/button';
import { ArrowLeft } from 'lucide-react';
import { __ } from '@/lib/i18n';
import { DynamicComponentLoader } from '@/components/DynamicComponentLoader';

interface Module {
  id: string;
  label: string;
  description: string;
  has_settings: boolean;
  settings_component?: string;
}

export default function ModuleSettings() {
  const { moduleId } = useParams<{ moduleId: string }>();
  const navigate = useNavigate();
  const { settings, isLoading: settingsLoading, updateSettings } = useModuleSettings(moduleId || '');

  // Fetch module info
  const { data: modulesData } = useQuery({
    queryKey: ['modules'],
    queryFn: async () => {
      const response = await api.get('/modules');
      return response as { modules: Record<string, Module> };
    },
  });

  // Fetch settings schema
  const { data: schemaData } = useQuery({
    queryKey: ['module-schema', moduleId],
    queryFn: async () => {
      const response = await api.get(`/modules/${moduleId}/schema`);
      return response as { schema: FormSchema };
    },
    enabled: !!moduleId,
  });

  const module = modulesData?.modules?.[moduleId || ''];

  if (!module) {
    return (
      <SettingsLayout title={__('Module Settings')} isLoading={!modulesData}>
        <div className="text-center py-12">
          <p className="text-muted-foreground">{__('Module not found')}</p>
          <Button
            variant="outline"
            onClick={() => navigate('/settings/modules')}
            className="mt-4"
          >
            <ArrowLeft className="mr-2 h-4 w-4" />
            {__('Back to Modules')}
          </Button>
        </div>
      </SettingsLayout>
    );
  }

  if (!module.has_settings) {
    return (
      <SettingsLayout title={module.label}>
        <div className="text-center py-12">
          <p className="text-muted-foreground">
            {__('This module does not have any settings')}
          </p>
          <Button
            variant="outline"
            onClick={() => navigate('/settings/modules')}
            className="mt-4"
          >
            <ArrowLeft className="mr-2 h-4 w-4" />
            {__('Back to Modules')}
          </Button>
        </div>
      </SettingsLayout>
    );
  }

  // If module has custom component, load it dynamically
  if (module.settings_component) {
    return (
      <SettingsLayout
        title={`${module.label} ${__('Settings')}`}
        description={module.description}
      >
        <Button
          variant="ghost"
          onClick={() => navigate('/settings/modules')}
          className="mb-4"
        >
          <ArrowLeft className="mr-2 h-4 w-4" />
          {__('Back to Modules')}
        </Button>

        <DynamicComponentLoader
          componentUrl={module.settings_component}
          moduleId={moduleId || ''}
        />
      </SettingsLayout>
    );
  }

  // Otherwise, render schema-based form
  return (
    <SettingsLayout
      title={`${module.label} ${__('Settings')}`}
      description={module.description}
      isLoading={settingsLoading}
    >
      <Button
        variant="ghost"
        onClick={() => navigate('/settings/modules')}
        className="mb-4"
      >
        <ArrowLeft className="mr-2 h-4 w-4" />
        {__('Back to Modules')}
      </Button>

      <SettingsCard
        title={__('Configuration')}
        description={__('Configure module settings below')}
      >
        {schemaData?.schema ? (
          <SchemaForm
            schema={schemaData.schema}
            initialValues={settings}
            onSubmit={(values) => updateSettings.mutate(values)}
            isSubmitting={updateSettings.isPending}
          />
        ) : (
          <div className="text-center py-8 text-muted-foreground">
            <p>{__('No settings schema available for this module')}</p>
            <p className="text-xs mt-2">
              {__('The module developer needs to register a settings schema using the woonoow/module_settings_schema filter')}
            </p>
          </div>
        )}
      </SettingsCard>
    </SettingsLayout>
  );
}
