"use client"

import React from 'react'
import { Layout, Palette, RotateCcw, Settings, X } from 'lucide-react'
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 { toast } from 'sonner'
import { saveUserPrefsAction } from '@/lib/appwrite/user-prefs-actions'
import type { UserPrefs as ThemePrefs } from '@/lib/appwrite/user-prefs-actions'
import { getLocalThemePrefs, saveLocalThemePrefs } from '@/lib/local-theme-prefs'
import { ThemeTab } from './theme-tab'
import { LayoutTab } from './layout-tab'
import { ImportModal } from './import-modal'
import { cn } from '@/lib/utils'
import type { ImportedTheme } from '@/types/theme-customizer'

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, updateConfig: updateSidebarConfig } = useSidebarConfig()

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

  // Sidebar config → sadece localStorage (Appwrite tetiklemesi döngüye yol açıyordu:
  // PrefsInitializer mount'ta updateConfig çağırıyor → bu effect server action tetikliyor
  // → Next.js router cache revalidation → remount → döngü)
  const sidebarMountRef = React.useRef(false)
  React.useEffect(() => {
    if (!sidebarMountRef.current) { sidebarMountRef.current = true; return }
    saveLocalThemePrefs({
      sidebarVariant: sidebarConfig.variant,
      sidebarCollapsible: sidebarConfig.collapsible,
      sidebarSide: sidebarConfig.side,
    })
  }, [sidebarConfig.variant, sidebarConfig.collapsible, sidebarConfig.side])

  const savePrefs = (update: Parameters<typeof saveUserPrefsAction>[0]) => {
    saveUserPrefsAction(update).then((res) => {
      if (!res.ok) toast.error("Tercihler kaydedilemedi: " + res.error)
    })
  }

  const handleReset = () => {
    setSelectedTheme("default")
    setSelectedTweakcnTheme("")
    setSelectedRadius("0.5rem")
    setImportedTheme(null)
    setBrandColorsValues({})
    resetTheme()
    applyRadius("0.5rem")
    updateSidebarConfig({ variant: "inset", collapsible: "offcanvas", side: "left" })
    saveLocalThemePrefs({ colorTheme: "default", tweakcnTheme: "", radius: "0.5rem", sidebarVariant: "inset", sidebarCollapsible: "offcanvas", sidebarSide: "left" })
    savePrefs({ colorTheme: "default", tweakcnTheme: "", radius: "0.5rem", sidebarVariant: "inset", sidebarCollapsible: "offcanvas", sidebarSide: "left" })
  }

  const handleImport = (themeData: ImportedTheme) => {
    setImportedTheme(themeData)
    // Clear other selections to indicate custom import is active
    setSelectedTheme("")
    setSelectedTweakcnTheme("")

    // Apply the imported theme
    applyImportedTheme(themeData, isDarkMode)
  }

  const handleImportClick = () => {
    setImportModalOpen(true)
  }

  // Re-apply themes when theme mode changes
  React.useEffect(() => {
    if (importedTheme) {
      applyImportedTheme(importedTheme, isDarkMode)
    } else if (selectedTheme) {
      applyTheme(selectedTheme, isDarkMode)
    } else if (selectedTweakcnTheme) {
      const selectedPreset = tweakcnThemes.find(t => t.value === selectedTweakcnTheme)?.preset
      if (selectedPreset) {
        applyTweakcnTheme(selectedPreset, 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) => {
            // Prevent the sheet from closing when dialog is open
            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">
                <Settings 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"
                >
                  <RotateCcw 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">
                <ThemeTab
                  selectedTheme={selectedTheme}
                  setSelectedTheme={(value) => {
                    setSelectedTheme(value)
                    saveLocalThemePrefs({ colorTheme: value })
                    savePrefs({ colorTheme: value })
                  }}
                  selectedTweakcnTheme={selectedTweakcnTheme}
                  setSelectedTweakcnTheme={(value) => {
                    setSelectedTweakcnTheme(value)
                    saveLocalThemePrefs({ tweakcnTheme: value })
                    savePrefs({ tweakcnTheme: value })
                  }}
                  selectedRadius={selectedRadius}
                  setSelectedRadius={(value) => {
                    setSelectedRadius(value)
                    saveLocalThemePrefs({ radius: value })
                    savePrefs({ radius: value })
                  }}
                  setImportedTheme={setImportedTheme}
                  onImportClick={handleImportClick}
                  onThemeModeChange={(mode) => savePrefs({ theme: mode })}
                />
              </TabsContent>

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

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

// Floating trigger button - positioned dynamically based on sidebar side
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"
      )}
    >
      <Settings className="h-5 w-5" />
    </Button>
  )
}
