"use client"

import { Button } from "@/Components/UI/Button"
import { Input } from "@/Components/UI/Input"
import ThemeColorTemplates from "./ThemeColorTemplates"
import useTranslate from "@/hooks/useTranslate";

const rgbToHex = (rgb) => {
  if (rgb.startsWith("#")) return rgb

  const match = rgb.match(/rgb$$(\d+),\s*(\d+),\s*(\d+)$$$/)
  if (!match) return rgb

  const [, r, g, b] = match
  return `#${((1 << 24) + (Number.parseInt(r) << 16) + (Number.parseInt(g) << 8) + Number.parseInt(b)).toString(16).slice(1)}`
}

const isValidHex = (hex) => {
  return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex)
}

const normalizeColor = (color) => {
  if (!color) return "#7f56d9"

  if (color.startsWith("rgb")) {
    return rgbToHex(color)
  }

  if (!color.startsWith("#")) {
    color = "#" + color
  }

  return isValidHex(color) ? color : "#7f56d9"
}

export default function ThemeSetting({ themeData, onThemeChange, onSubmit, onReset, isSubmitting }) {
  const getThemeValue = (field) => {
    return themeData?.[field] || "#7f56d9"
  }

  const handleColorChange = (field, value) => {
    if (typeof onThemeChange !== "function") {
      console.error("onThemeChange is not a function:", onThemeChange)
      return
    }

    const normalizedValue = normalizeColor(value)

    onThemeChange(field, normalizedValue)
  }

  const handleTextChange = (field, value) => {
    if (typeof onThemeChange !== "function") {
      console.error("onThemeChange is not a function:", onThemeChange)
      return
    }

    onThemeChange(field, value)
  }

  const handleTextBlur = (field, value) => {
    const normalizedValue = normalizeColor(value)
    if (normalizedValue !== value) {
      onThemeChange(field, normalizedValue)
    }
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    onSubmit()
  }

  const handleReset = () => {
    onReset()
  }

  const handleTemplateSelect = (templateColors) => {
    Object.keys(templateColors).forEach(key => {
      onThemeChange(key, templateColors[key])
    })
  }

  const t = useTranslate()

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">{t("Interface & Design")}</h3>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {t("Customize your application's visual appearance and branding")}
          </p>
        </div>
        <div className="flex gap-3">
          <Button
            variant="outline"
            className="px-4 py-2.5 border border-gray-300 dark:border-zinc-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-zinc-800 rounded-lg font-medium transition-colors"
            onClick={handleReset}
          >
            {t("Reset")}
          </Button>
          <Button
            isLoading={isSubmitting}
            className="bg-gradient-to-r from-primary to-secondary hover:from-primary/90 hover:to-secondary/90 text-white px-6 py-2.5 rounded-lg font-medium shadow-sm transition-all duration-200 flex items-center gap-2"
            onClick={handleSubmit}
          >
            {!isSubmitting && (
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            )}
            {isSubmitting ? t("Saving...") : t("Save Changes")}
          </Button>
        </div>
      </div>

      {/* Professional Theme Templates */}
      <ThemeColorTemplates
        onTemplateSelect={handleTemplateSelect}
        currentTheme={themeData}
      />

      {/* Divider */}
      <div className="border-t border-gray-200 dark:border-zinc-800 pt-8">
        <h3 className="text-lg font-semibold text-bodyTextPrimary dark:text-neutral-200 mb-6">
          {t("Custom Color Settings")}
        </h3>
      <div className="grid md:grid-cols-2 grid-cols-1 lg:gap-6 gap-4">
        {/* Left Column */}
        <div className="space-y-6">
          <div>
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-neutral-400 mb-3">{t("Primary Color")}</label>
            <div className="relative">
              <Input
                type="text"
                value={getThemeValue("primary_color")}
                onChange={(e) => handleTextChange("primary_color", e.target.value)}
                onBlur={(e) => handleTextBlur("primary_color", e.target.value)}
                className="bg-gray-50 border-gray-200 pl-14 font-mono dark:bg-zinc-800 dark:border-none dark:text-neutral-200"
                placeholder="#000000"
              />
              <div className="absolute left-3 top-1/2 transform -translate-y-1/2">
                <input
                  type="color"
                  value={normalizeColor(getThemeValue("primary_color"))}
                  onChange={(e) => {
                    handleColorChange("primary_color", e.target.value)
                  }}
                  className="w-6 h-6 rounded border border-gray-300 cursor-pointer"
                  style={{ background: "transparent" }}
                />
              </div>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-neutral-400 mb-3">{t("Primary Color Text")}</label>
            <div className="relative">
              <Input
                type="text"
                value={getThemeValue("primary_color_text")}
                onChange={(e) => handleTextChange("primary_color_text", e.target.value)}
                onBlur={(e) => handleTextBlur("primary_color_text", e.target.value)}
                className="bg-gray-50 border-gray-200 pl-14 font-mono dark:bg-zinc-800 dark:border-none dark:text-neutral-200"
                placeholder="#000000"
              />
              <div className="absolute left-3 top-1/2 transform -translate-y-1/2">
                <input
                  type="color"
                  value={normalizeColor(getThemeValue("primary_color_text"))}
                  onChange={(e) => {
                    handleColorChange("primary_color_text", e.target.value)
                  }}
                  className="w-6 h-6 rounded border border-gray-300 cursor-pointer"
                  style={{ background: "transparent" }}
                />
              </div>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-neutral-400 mb-3">{t("Body Text Primary")}</label>
            <div className="relative">
              <Input
                type="text"
                value={getThemeValue("body_text_primary")}
                onChange={(e) => handleTextChange("body_text_primary", e.target.value)}
                onBlur={(e) => handleTextBlur("body_text_primary", e.target.value)}
                className="bg-gray-50 border-gray-200 pl-14 font-mono dark:bg-zinc-800 dark:border-none dark:text-neutral-200"
                placeholder="#000000"
              />
              <div className="absolute left-3 top-1/2 transform -translate-y-1/2">
                <input
                  type="color"
                  value={normalizeColor(getThemeValue("body_text_primary"))}
                  onChange={(e) => {
                    handleColorChange("body_text_primary", e.target.value)
                  }}
                  className="w-6 h-6 rounded border border-gray-300 cursor-pointer"
                  style={{ background: "transparent" }}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Right Column */}
        <div className="space-y-6">
          <div>
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-neutral-400 mb-3">{t("Secondary Color")}</label>
            <div className="relative">
              <Input
                type="text"
                value={getThemeValue("secondary_color")}
                onChange={(e) => handleTextChange("secondary_color", e.target.value)}
                onBlur={(e) => handleTextBlur("secondary_color", e.target.value)}
                className="bg-gray-50 border-gray-200 pl-14 font-mono dark:bg-zinc-800 dark:border-none dark:text-neutral-200"
                placeholder="#000000"
              />
              <div className="absolute left-3 top-1/2 transform -translate-y-1/2">
                <input
                  type="color"
                  value={normalizeColor(getThemeValue("secondary_color"))}
                  onChange={(e) => {
                    handleColorChange("secondary_color", e.target.value)
                  }}
                  className="w-6 h-6 rounded border border-gray-300 cursor-pointer"
                  style={{ background: "transparent" }}
                />
              </div>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-neutral-400 mb-3">{t("Secondary Color Text")}</label>
            <div className="relative">
              <Input
                type="text"
                value={getThemeValue("secondary_color_text")}
                onChange={(e) => handleTextChange("secondary_color_text", e.target.value)}
                onBlur={(e) => handleTextBlur("secondary_color_text", e.target.value)}
                className="bg-gray-50 border-gray-200 pl-14 font-mono dark:bg-zinc-800 dark:border-none dark:text-neutral-200"
                placeholder="#000000"
              />
              <div className="absolute left-3 top-1/2 transform -translate-y-1/2">
                <input
                  type="color"
                  value={normalizeColor(getThemeValue("secondary_color_text"))}
                  onChange={(e) => {
                    handleColorChange("secondary_color_text", e.target.value)
                  }}
                  className="w-6 h-6 rounded border border-gray-300 cursor-pointer"
                  style={{ background: "transparent" }}
                />
              </div>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-neutral-400 mb-3">{t("Body Text Secondary")}</label>
            <div className="relative">
              <Input
                type="text"
                value={getThemeValue("body_text_secondary")}
                onChange={(e) => handleTextChange("body_text_secondary", e.target.value)}
                onBlur={(e) => handleTextBlur("body_text_secondary", e.target.value)}
                className="bg-gray-50 border-gray-200 pl-14 font-mono dark:bg-zinc-800 dark:border-none dark:text-neutral-200"
                placeholder="#000000"
              />
              <div className="absolute left-3 top-1/2 transform -translate-y-1/2">
                <input
                  type="color"
                  value={normalizeColor(getThemeValue("body_text_secondary"))}
                  onChange={(e) => {
                    handleColorChange("body_text_secondary", e.target.value)
                  }}
                  className="w-6 h-6 rounded border border-gray-300 cursor-pointer"
                  style={{ background: "transparent" }}
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      </div> {/* Close custom color settings div */}
    </div>
  )
}
