/**
 * Checkout Field Editor Main Settings Page
 */

import { useState } from "react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { 
  FormInput, 
  Settings, 
  Loader2,
  AlertCircle,
  Zap
} from "lucide-react"
import { toast } from "sonner"
import { FeatureHeader } from "@/components/feature-header"
import { useFieldEditor } from "../hooks/use-field-editor"
import { EditorTab } from "./tabs/editor-tab"
import { SettingsTab } from "./tabs/settings-tab"
import { ConditionalLogicTab } from "./tabs/conditional-logic-tab"
import { FieldEditorUpgradeTab } from "./tabs/upgrade-tab"
import { ProIndicator } from "@/components/pro/pro-indicator"
import { Crown } from "lucide-react"
import { usePro } from "@/contexts/pro-context"
import type { CheckoutField } from "../config"

const FIELD_EDITOR_DOCS_URL = "https://www.swiftcommerce.io/help/checkout/checkout-field-editor/"

export function FieldEditorSettings() {
  const { isPro } = usePro()
  const [activeTab, setActiveTab] = useState('editor')
  const [editingFieldFromCL, setEditingFieldFromCL] = useState<CheckoutField | null>(null)
  const {
    settings,
    fields,
    sections,
    isLoading,
    isSaving,
    error,
    hasChanges,
    updateSettings,
    addField,
    updateField,
    deleteField,
    duplicateField,
    toggleFieldEnabled,
    reorderFields,
    moveFieldToSection,
    updateSection,
    toggleSectionEnabled,
    saveSettings,
    resetToDefaults,
    exportSettings,
    importSettings
  } = useFieldEditor()

  const handleSave = async () => {
    const success = await saveSettings()
    if (success) {
      toast.success("Settings saved", {
        description: "Your checkout field editor settings have been saved successfully."
      })
    } else {
      toast.error("Failed to save settings", {
        description: "Please try again or check your connection."
      })
    }
  }

  const handleReset = () => {
    resetToDefaults()
    toast.success("Settings reset", {
      description: "All settings have been reset to their defaults. Don't forget to save."
    })
  }

  if (isLoading) {
    return (
      <div className="flex flex-1 items-center justify-center p-8">
        <div className="flex items-center gap-2 text-muted-foreground">
          <Loader2 className="h-5 w-5 animate-spin" />
          <span>Loading checkout field editor...</span>
        </div>
      </div>
    )
  }

  return (
    <FeatureHeader
      icon={<FormInput className="h-6 w-6" />}
      title="Checkout Field Editor"
      description="Customize checkout fields, add new fields, and control validation"
      documentationUrl={FIELD_EDITOR_DOCS_URL}
      enabled={settings.enabled}
      onEnabledChange={(checked) => updateSettings('enabled', checked)}
      hasChanges={hasChanges}
      isSaving={isSaving}
      onSave={handleSave}
      onReset={handleReset}
    >
      <div className="flex flex-col gap-4">
        {/* Error Alert */}
        {error && (
          <div className="flex items-center gap-2 p-4 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg">
            <AlertCircle className="h-4 w-4" />
            {error}
          </div>
        )}

        {/* Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1">
          <TabsList>
            <TabsTrigger value="editor" className="flex items-center gap-2">
              <FormInput className="h-4 w-4" />
              Field Editor
            </TabsTrigger>
            <TabsTrigger value="settings" className="flex items-center gap-2">
              <Settings className="h-4 w-4" />
              Settings
            </TabsTrigger>
            {isPro && (
            <TabsTrigger value="conditional-logic" className="flex items-center gap-2">
              <Zap className="h-4 w-4" />
              Conditional Logic
              <ProIndicator size="sm" />
            </TabsTrigger>
            )}
            {!isPro && (
            <TabsTrigger
              value="upgrade"
              className="gap-2 text-white hover:text-white data-[state=active]:text-white data-[state=active]:shadow-none"
              style={{ backgroundColor: '#002269' }}
            >
              <Crown className="h-4 w-4" />
              Upgrade to Pro
            </TabsTrigger>
            )}
          </TabsList>

          <TabsContent value="editor" className="mt-4">
            <EditorTab
              fields={fields}
              sections={sections}
              addField={addField}
              updateField={updateField}
              deleteField={deleteField}
              duplicateField={duplicateField}
              toggleFieldEnabled={toggleFieldEnabled}
              reorderFields={reorderFields}
              moveFieldToSection={moveFieldToSection}
              updateSection={updateSection}
              toggleSectionEnabled={toggleSectionEnabled}
              editingFieldFromCL={editingFieldFromCL}
              clearEditingFieldFromCL={() => setEditingFieldFromCL(null)}
            />
          </TabsContent>

          <TabsContent value="settings" className="mt-4">
            <SettingsTab
              settings={settings}
              updateSettings={updateSettings}
              exportSettings={exportSettings}
              importSettings={importSettings}
            />
          </TabsContent>

          {isPro && (
          <TabsContent value="conditional-logic" className="mt-4">
            <ConditionalLogicTab
              fields={fields}
              onEditField={(field) => {
                setEditingFieldFromCL(field)
                setActiveTab('editor')
              }}
              updateField={updateField}
            />
          </TabsContent>
          )}

          {!isPro && (
          <TabsContent value="upgrade" className="mt-4">
            <FieldEditorUpgradeTab />
          </TabsContent>
          )}
        </Tabs>
      </div>
    </FeatureHeader>
  )
}
