"use client"

import React from 'react'
import { Layout, Palette, ArrowCounterClockwise, GearSix, X } from '@/lib/icons'
import { Button } from '@/components/ui/button'
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useThemeManager } from '@/hooks/use-theme-manager'
import { useTheme } from '@/hooks/use-theme'
import { useSidebarConfig } from '@/contexts/sidebar-context'
import { tweakcnThemes } from '@/config/theme-data'
import { ThemeTab } from './theme-tab'
import { LayoutTab } from './layout-tab'
import { ImportModal } from './import-modal'
import { saveThemePrefsAction } from '@/lib/appwrite/theme-prefs-actions'
import { cn } from '@/lib/utils'
import type { ImportedTheme } from '@/types/theme-customizer'
import type { ThemePrefs } from '@/lib/appwrite/theme-prefs-actions'

interface ThemeCustomizerProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  initialPrefs: ThemePrefs
}

export function ThemeCustomizer({ open, onOpenChange, initialPrefs }: ThemeCustomizerProps) {
  const { applyImportedTheme, isDarkMode, resetTheme, applyRadius, setBrandColorsValues, applyTheme, applyTweakcnTheme } = useThemeManager()
  const { theme } = useTheme()
  const { config: sidebarConfig } = useSidebarConfig()

  const [activeTab, setActiveTab] = React.useState("theme")
  const [selectedTheme, setSelectedTheme] = React.useState(initialPrefs.colorTheme ?? "default")
  const [selectedTweakcnTheme, setSelectedTweakcnTheme] = React.useState(initialPrefs.tweakcnTheme ?? "")
  const [selectedRadius, setSelectedRadius] = React.useState(initialPrefs.radius ?? "0.5rem")
  const [importModalOpen, setImportModalOpen] = React.useState(false)
  const [importedTheme, setImportedTheme] = React.useState<ImportedTheme | null>(null)

  // --- Appwrite persistence via useEffect (fires ONCE after React batches state updates) ---

  const darkModeSaveMountRef = React.useRef(false)
  React.useEffect(() => {
    if (!darkModeSaveMountRef.current) { darkModeSaveMountRef.current = true; return }
    void saveThemePrefsAction({ theme })
  }, [theme])

  const colorThemeSaveMountRef = React.useRef(false)
  React.useEffect(() => {
    if (!colorThemeSaveMountRef.current) { colorThemeSaveMountRef.current = true; return }
    void saveThemePrefsAction({ colorTheme: selectedTheme, tweakcnTheme: selectedTweakcnTheme })
  }, [selectedTheme, selectedTweakcnTheme])

  const radiusSaveMountRef = React.useRef(false)
  React.useEffect(() => {
    if (!radiusSaveMountRef.current) { radiusSaveMountRef.current = true; return }
    void saveThemePrefsAction({ radius: selectedRadius })
  }, [selectedRadius])

  const sidebarSaveMountRef = React.useRef(false)
  React.useEffect(() => {
    if (!sidebarSaveMountRef.current) { sidebarSaveMountRef.current = true; return }
    void saveThemePrefsAction({
      sidebarVariant: sidebarConfig.variant,
      sidebarCollapsible: sidebarConfig.collapsible,
      sidebarSide: sidebarConfig.side,
    })
  }, [sidebarConfig.variant, sidebarConfig.collapsible, sidebarConfig.side])

  // --- Theme reset ---

  const handleReset = () => {
    setSelectedTheme("default")
    setSelectedTweakcnTheme("")
    setSelectedRadius("0.5rem")
    setImportedTheme(null)
    setBrandColorsValues({})
    resetTheme()
    applyRadius("0.5rem")
    // colorThemeSaveEffect and radiusSaveEffect will fire via the state changes above
  }

  const handleImport = (themeData: ImportedTheme) => {
    setImportedTheme(themeData)
    setSelectedTheme("")
    setSelectedTweakcnTheme("")
    applyImportedTheme(themeData, isDarkMode)
    // Imported themes have no stable identifier to persist
  }

  // Re-apply when dark/light toggles
  React.useEffect(() => {
    if (importedTheme) {
      applyImportedTheme(importedTheme, isDarkMode)
    } else if (selectedTheme) {
      applyTheme(selectedTheme, isDarkMode)
    } else if (selectedTweakcnTheme) {
      const preset = tweakcnThemes.find(t => t.value === selectedTweakcnTheme)?.preset
      if (preset) applyTweakcnTheme(preset, isDarkMode)
    }
  }, [isDarkMode, importedTheme, selectedTheme, selectedTweakcnTheme, applyImportedTheme, applyTheme, applyTweakcnTheme])

  return (
    <>
      <Sheet open={open} onOpenChange={onOpenChange} modal={false}>
        <SheetContent
          side={sidebarConfig.side === "left" ? "right" : "left"}
          className="w-[400px] p-0 gap-0 pointer-events-auto [&>button]:hidden overflow-hidden flex flex-col"
          onInteractOutside={(e) => {
            if (importModalOpen) e.preventDefault()
          }}
        >
          <SheetHeader className="space-y-0 p-4 pb-2">
            <div className="flex items-center gap-2">
              <div className="p-2 bg-primary/10 rounded-lg">
                <GearSix className="h-4 w-4" />
              </div>
              <SheetTitle className="text-lg font-semibold">Görünüm</SheetTitle>
              <div className="ml-auto flex items-center gap-2">
                <Button
                  variant="outline"
                  size="icon"
                  onClick={handleReset}
                  className="cursor-pointer h-8 w-8"
                  aria-label="Varsayılana dön"
                  title="Varsayılana dön"
                >
                  <ArrowCounterClockwise className="h-4 w-4" />
                </Button>
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => onOpenChange(false)}
                  className="cursor-pointer h-8 w-8"
                  aria-label="Kapat"
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>
            <SheetDescription className="text-sm text-muted-foreground sr-only">
              Panelin renklerini ve düzenini özelleştirin.
            </SheetDescription>
          </SheetHeader>

          <div className="flex-1 overflow-y-auto">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="h-full flex flex-col">
              <div className="py-2">
                <TabsList className="grid w-full grid-cols-2 rounded-none h-12 p-1.5">
                  <TabsTrigger value="theme" className="cursor-pointer data-[state=active]:bg-background">
                    <Palette className="h-4 w-4 mr-1" /> Renk
                  </TabsTrigger>
                  <TabsTrigger value="layout" className="cursor-pointer data-[state=active]:bg-background">
                    <Layout className="h-4 w-4 mr-1" /> Düzen
                  </TabsTrigger>
                </TabsList>
              </div>

              <TabsContent value="theme" className="flex-1 mt-0">
                {/* Pass RAW state setters — ThemeTab handles cross-clearing itself.
                    Appwrite persistence is handled by the useEffects above, which fire
                    once after React batches all state updates in the event handler. */}
                <ThemeTab
                  selectedTheme={selectedTheme}
                  setSelectedTheme={setSelectedTheme}
                  selectedTweakcnTheme={selectedTweakcnTheme}
                  setSelectedTweakcnTheme={setSelectedTweakcnTheme}
                  selectedRadius={selectedRadius}
                  setSelectedRadius={setSelectedRadius}
                  setImportedTheme={setImportedTheme}
                  onImportClick={() => setImportModalOpen(true)}
                />
              </TabsContent>

              <TabsContent value="layout" className="flex-1 mt-0">
                <LayoutTab />
              </TabsContent>
            </Tabs>
          </div>
        </SheetContent>
      </Sheet>

      <ImportModal
        open={importModalOpen}
        onOpenChange={setImportModalOpen}
        onImport={handleImport}
      />
    </>
  )
}

export function ThemeCustomizerTrigger({ onClick }: { onClick: () => void }) {
  const { config: sidebarConfig } = useSidebarConfig()

  return (
    <Button
      onClick={onClick}
      size="icon"
      className={cn(
        "fixed top-1/2 -translate-y-1/2 h-12 w-12 rounded-full shadow-lg z-50 bg-primary hover:bg-primary/90 text-primary-foreground cursor-pointer",
        sidebarConfig.side === "left" ? "right-4" : "left-4"
      )}
    >
      <GearSix className="h-5 w-5" />
    </Button>
  )
}
