"use client"

import { useState, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"
import PremiumSettingsSidebar from "@/Components/AppSettings/PremiumSettingsSidebar"
import PremiumSettingsTabs from "@/Components/AppSettings/PremiumSettingsTabs"
import PremiumSettingsCard, { SettingsRow, SettingsSection, ToggleCard } from "@/Components/UI/PremiumSettingsCard"
import BasicSetting from "@/Components/AppSettings/BasicSetting"
import ThemeSetting from "@/Components/AppSettings/ThemeSetting"
import LogoSetting from "@/Components/AppSettings/LogoSetting"
import Logging from "@/Components/AppSettings/Logging"
import TextModule from "@/Components/AiConfiguration/TextModule"
import ImageModule from "@/Components/AiConfiguration/ImageModule"
import VideoModule from "@/Components/AiConfiguration/VideoModule"
import AiConfigurationTabs from "@/Components/AiConfiguration/AiConfigurationTabs"
import Local from "@/Components/StorageSettings/Local"
import AwsS3 from "@/Components/StorageSettings/AwsS3"
import Ftp from "@/Components/StorageSettings/Ftp"
import StorageSettingsTabs from "@/Components/StorageSettings/StorageSettingsTabs"
import Languages from "@/Components/Languages"
import EmailSettings from "@/Components/AppSettings/EmailSettings"
import SecuritySettings from "@/Components/AppSettings/SecuritySettings"
import BackupSettings from "@/Components/AppSettings/BackupSettings"
import AppLayout from "@/Layouts/AppLayout"
import { camelCase } from "lodash";
import { router } from "@inertiajs/react"
import useTranslate from "@/hooks/useTranslate";


export default function SettingsPage(
  {
    settings,
    settingConfig,
    aiSettings,
    languages
  }
) {
  const [activeSection, setActiveSection] = useState("app-setting")
  const [activeTab, setActiveTab] = useState("basic-setting")
  const [activeAiTab, setActiveAiTab] = useState("text-module")
  const [activeStorageTab, setActiveStorageTab] = useState("local")
  const [isSubmitting, setIsSubmitting] = useState(false)

  const textAiSetting = aiSettings.find(s => s.module === "text_ai")
  const imageAiSetting = aiSettings.find(s => s.module === "image_ai")
  const videoAiSetting = aiSettings.find(s => s.module === "video_ai")

  const t = useTranslate();



  const breadcrumbs = [
    { 
      label: t("Dashboard"), 
      href: "/user/dashboard",
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
        </svg>
      )
    },
    { 
      label: t("Settings"),
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
        </svg>
      )
    }
  ]

  const [formData, setFormData] = useState({
    site_name: settings.site_name ,
    phone: settings.phone ,
    phone_code: settings.phone_code ,
    email: settings.email ,
    country: settings.country ,
    address: settings.address ,
    time_zone: settings.time_zone ,
    date_format: settings.date_format ,
    data_per_page: settings.data_per_page ,
  });

  const [themeData, setThemeData] = useState({
    primary_color: settings.primary_color ?? "#667eea",
    secondary_color: settings.secondary_color ?? "#764ba2",
    primary_color_text: settings.primary_color_text ?? "#ffffff",
    secondary_color_text: settings.secondary_color_text ?? "#ffffff",
    body_text_primary: settings.body_text_primary ?? "#1a202c",
    body_text_secondary: settings.body_text_secondary ?? "#718096",
  })

  const handleInputChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }))
  }

  const handleThemeChange = (field, value) => {
    setThemeData((prev) => ({ ...prev, [field]: value }))
  }

  const handleSubmit = () => {
    setIsSubmitting(true)
    router.post(route('user.setting.store'), formData, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const handleThemeSubmit = () => {
    
    setIsSubmitting(true)
    router.post(route('user.setting.store'), themeData, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const handleThemeReset = () => {
    setThemeData({
      primary_color: "#667eea",
      secondary_color: "#764ba2",
      primary_color_text: "#ffffff",
      secondary_color_text: "#ffffff",
      body_text_primary: "#1a202c", 
      body_text_secondary: "#718096",
    })
  }

  const renderTabContent = () => {
    switch (activeTab) {
      case "basic-setting":
        return <BasicSetting formData={formData} onInputChange={handleInputChange} onSubmit={handleSubmit} isSubmitting={isSubmitting} />
      case "theme-setting":
        return (
          <ThemeSetting
            themeData={themeData}
            onThemeChange={handleThemeChange}
            onSubmit={handleThemeSubmit}
            onReset={handleThemeReset}
            isSubmitting={isSubmitting}
          />
        )
      case "logo-setting":
        return <LogoSetting />
      case "logging":
        return <Logging settings={settings} />
      default:
        return null
    }
  }

  const renderAiTabContent = () => {
    switch (activeAiTab) {
      case "text-module":
        return <TextModule settingConfig={settingConfig} textAiSetting={textAiSetting} />
      case "image-module":
        return <ImageModule settingConfig={settingConfig} imageAiSetting={imageAiSetting} />
      case "video-module":
        return <VideoModule settingConfig={settingConfig} videoAiSetting={videoAiSetting} />
      default:
        return null
    }
  }

  const renderStorageTabContent = () => {
    switch (activeStorageTab) {
      case "local":
        return <Local />
      case "aws-s3":
        return <AwsS3 />
      case "ftp":
        return <Ftp />
      default:
        return null
    }
  }

  const renderSectionContent = () => {
    if (activeSection === "ai-configuration") {
      return (
        <PremiumSettingsCard
          title={t("AI Configuration")}
          description={t("Configure AI modules and settings")}
          icon={
            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
              <path d="M13 7H7v6h6V7z" />
              <path fillRule="evenodd" d="M7 2a1 1 0 012 0v1h2V2a1 1 0 112 0v1h2a2 2 0 012 2v2h1a1 1 0 110 2h-1v2h1a1 1 0 110 2h-1v2a2 2 0 01-2 2h-2v1a1 1 0 11-2 0v-1H9v1a1 1 0 11-2 0v-1H5a2 2 0 01-2-2v-2H2a1 1 0 110-2h1V9H2a1 1 0 010-2h1V5a2 2 0 012-2h2V2z" clipRule="evenodd" />
            </svg>
          }
        >
          <AiConfigurationTabs activeTab={activeAiTab} onTabChange={setActiveAiTab} />
          <div className="p-6">{renderAiTabContent()}</div>
        </PremiumSettingsCard>
      )
    }

    if (activeSection === "storage-setting") {
      return (
        <PremiumSettingsCard
          title={t("Storage & Media")}
          description={t("Configure storage providers and media settings")}
          icon={
            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
              <path d="M3 12v3c0 1.657 3.134 3 7 3s7-1.343 7-3v-3c0 1.657-3.134 3-7 3s-7-1.343-7-3z" />
              <path d="M3 7v3c0 1.657 3.134 3 7 3s7-1.343 7-3V7c0 1.657-3.134 3-7 3S3 8.657 3 7z" />
              <path d="M17 5c0 1.657-3.134 3-7 3S3 6.657 3 5s3.134-3 7-3 7 1.343 7 3z" />
            </svg>
          }
        >
          <StorageSettingsTabs activeTab={activeStorageTab} onTabChange={setActiveStorageTab} />
          <div className="p-6">{renderStorageTabContent()}</div>
        </PremiumSettingsCard>
      )
    }

    if (activeSection === "languages") {
      return (
        <PremiumSettingsCard
          title={t("Language & Region")}
          description={t("Manage languages and regional settings")}
          icon={
            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M7 2a1 1 0 011 1v1h3a1 1 0 110 2H9.578a18.87 18.87 0 01-1.724 4.78c.29.354.596.696.914 1.026a1 1 0 11-1.44 1.389c-.188-.196-.373-.396-.554-.6a19.098 19.098 0 01-3.107 3.567 1 1 0 01-1.334-1.49 17.087 17.087 0 003.13-3.733 18.992 18.992 0 01-1.487-2.494 1 1 0 111.79-.89c.234.47.489.928.764 1.372.417-.934.752-1.913.997-2.927H3a1 1 0 110-2h3V3a1 1 0 011-1zm6 6a1 1 0 01.894.553l2.991 5.982a.869.869 0 01.02.037l.99 1.98a1 1 0 11-1.79.895L15.383 16h-4.764l-.724 1.447a1 1 0 11-1.788-.894l.99-1.98.019-.038 2.99-5.982A1 1 0 0113 8zm-1.382 6h2.764L13 11.236 11.618 14z" clipRule="evenodd" />
            </svg>
          }
        >
          <Languages languages={languages} />
        </PremiumSettingsCard>
      )
    }

    if (activeSection === "mail-setting") {
      return (
        <PremiumSettingsCard
          title={t("System Email Configuration")}
          description={t("Configure SMTP settings and email templates")}
          icon={
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 8l7.89 7.89a2 2 0 002.82 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
            </svg>
          }
        >
          <EmailSettings settings={settings} />
        </PremiumSettingsCard>
      )
    }

    if (activeSection === "security") {
      return (
        <PremiumSettingsCard
          title={t("Security & Privacy")}
          description={t("Manage security settings and privacy controls")}
          icon={
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          }
        >
          <SecuritySettings settings={settings} />
        </PremiumSettingsCard>
      )
    }

    if (activeSection === "backup-setting") {
      return (
        <PremiumSettingsCard
          title={t("Backup & Maintenance")}
          description={t("System backup and maintenance operations")}
          icon={
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" />
            </svg>
          }
        >
          <BackupSettings settings={settings} />
        </PremiumSettingsCard>
      )
    }

    return (
      <PremiumSettingsCard
        title={t("Application Settings")}
        description={t("Configure general application settings and preferences")}
        icon={
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          </svg>
        }
      >
        <PremiumSettingsTabs
          activeTab={activeTab}
          onTabChange={setActiveTab}
          tabs={[
            { id: "basic-setting", label: t("Application Configuration") },
            { id: "theme-setting", label: t("Interface & Design") },
            { id: "logo-setting", label: t("Brand Management") },
            { id: "logging", label: t("System Monitoring") },
          ]}
        />
        <div className="p-6">{renderTabContent()}</div>
      </PremiumSettingsCard>
    )
  }

  return (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="min-h-screen bg-gray-50 dark:bg-zinc-950">
        {/* Premium Header */}
        <div className="bg-white dark:bg-zinc-900 border-b border-gray-200 dark:border-zinc-800">
          <div className="px-0 py-0">
            <div className="flex items-center justify-between">
              <div>
                <motion.h1 
                  initial={{ opacity: 0, y: -20 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="text-xl sm:text-2xl dark:text-gray-200 font-bold"
                >
                  {t("Settings")}
                </motion.h1>
                <motion.p 
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.1 }}
                  className="mt-2 text-gray-500 dark:text-gray-400"
                >
                  {t("Manage your application preferences and configurations")}
                </motion.p>
              </div>
              
              {/* Quick Actions */}
              <motion.div 
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: 0.2 }}
                className="flex items-center space-x-3"
              >
                <button
                  className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-zinc-800 border border-gray-300 dark:border-zinc-700 rounded-lg hover:bg-gray-50 dark:hover:bg-zinc-700 transition-colors flex items-center space-x-2"
                  onClick={() => router.get(route('user.profile.settings'))}
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                  </svg>
                  <span>{t("Profile")}</span>
                </button>
                
                <button className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-zinc-800 border border-gray-300 dark:border-zinc-700 rounded-lg hover:bg-gray-50 dark:hover:bg-zinc-700 transition-colors flex items-center space-x-2">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <span>{t("Help")}</span>
                </button>
              </motion.div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="px-6 py-8">
          <div className="max-w-full mx-auto">
            <div className="flex gap-6 flex-wrap">
              {/* Premium Sidebar */}
              <PremiumSettingsSidebar 
                activeSection={activeSection} 
                onSectionChange={setActiveSection} 
              />

              {/* Content Area */}
              <motion.div 
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: 0.3 }}
                className="flex-1"
              >
                {renderSectionContent()}
              </motion.div>
            </div>
          </div>
        </div>
      </div>
    </AppLayout>
  )
}