'use client'

import { useState } from 'react'
import { StepHeader } from '@/components/sdk/StepHeader'

import { EmailTemplate, TabId } from './_types'
import { useEmailTemplates } from './_hooks/useEmailTemplates'
import { TabNav } from './_components/TabNav'
import { TemplatesTab } from './_components/TemplatesTab'
import { EditorTab } from './_components/EditorTab'
import { SettingsTab } from './_components/SettingsTab'
import { LogsTab } from './_components/LogsTab'

export default function EmailTemplatesPage() {
  const [activeTab, setActiveTab] = useState<TabId>('templates')
  const {
    templates, logs, logsTotal, loading, error,
    selectedCategory,
    selectedTemplate, editorSubject, editorHtml, editorVersion, saving, previewHtml,
    settingsForm, savingSettings,
    setError, setSelectedCategory,
    setEditorSubject, setEditorHtml,
    setSettingsForm,
    openEditor, saveVersion, publishVersion, loadPreview,
    submitForReview, approveVersion, rejectVersion,
    sendTestEmail, loadApprovalHistory,
    saveSettings2, initializeDefaults,
  } = useEmailTemplates(activeTab)

  const handleEdit = async (template: EmailTemplate) => {
    setActiveTab('editor')
    await openEditor(template)
  }

  return (
    <div className="space-y-6">
      <StepHeader stepId="email-templates" />

      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">
          {error}
          <button onClick={() => setError(null)} className="ml-2 underline">Schliessen</button>
        </div>
      )}

      <TabNav activeTab={activeTab} onTabChange={setActiveTab} logsTotal={logsTotal} />

      {activeTab === 'templates' && (
        <TemplatesTab
          templates={templates}
          loading={loading}
          selectedCategory={selectedCategory}
          onCategoryChange={setSelectedCategory}
          onEdit={handleEdit}
          onInitialize={initializeDefaults}
        />
      )}

      {activeTab === 'editor' && (
        <EditorTab
          template={selectedTemplate}
          version={editorVersion}
          subject={editorSubject}
          html={editorHtml}
          previewHtml={previewHtml}
          saving={saving}
          onSubjectChange={setEditorSubject}
          onHtmlChange={setEditorHtml}
          onSave={saveVersion}
          onPublish={publishVersion}
          onPreview={loadPreview}
          onBack={() => setActiveTab('templates')}
          onSubmitForReview={submitForReview}
          onApprove={approveVersion}
          onReject={rejectVersion}
          onSendTest={sendTestEmail}
        />
      )}

      {activeTab === 'settings' && settingsForm && (
        <SettingsTab
          settings={settingsForm}
          saving={savingSettings}
          onChange={setSettingsForm}
          onSave={saveSettings2}
        />
      )}

      {activeTab === 'logs' && (
        <LogsTab logs={logs} total={logsTotal} />
      )}
    </div>
  )
}
