"use client"

import { useState, useEffect } from "react"
import { Button } from "@/Components/UI/Button"
import { RSelect } from "@/Components/UI/RSelect"
import { Input } from "@/Components/UI/Input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/UI/Select"
import { Plus } from "lucide-react"
import { router } from "@inertiajs/react"
import useTranslate from "@/hooks/useTranslate";
import { RSelectCreatable } from "@/Components/UI/RSelectCreatable"

export default function TextModule({ textAiSetting, settingConfig }) {

  const t = useTranslate()


  const [isSubmitting, setIsSubmitting] = useState(false)


  const [textData, setTextData] = useState({
    module: "text_ai",
    provider: "open_ai",
    config: {
      model: "",
      default_tone: "",
      default_creativity: "",
      bad_words: [],
      max_result: "150",
      api_key: ""
    }
  })

  useEffect(() => {
    if (textAiSetting) {
      setTextData(textAiSetting)
    }
  }, [textAiSetting])




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


  const handleSubmit = () => {
    setIsSubmitting(true)

    router.post(route('user.ai_setting.store'), textData, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const handleAddNewKey = () => {
  }

  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("Text AI Configuration")}</h3>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
            {t("Configure OpenAI text generation settings and parameters")}
          </p>
        </div>
        <Button
          isLoading={isSubmitting}
          onClick={handleSubmit}
          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"
        >
          {!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 Configuration")}
        </Button>
      </div>

      <div className="space-y-6">
        {/* First Row - Select Fields (Half Width) */}
        <div className="grid lg:grid-cols-2 grid-cols-1 lg:gap-6 gap-4">
          <div className="col-span-1">
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-gray-200 mb-2">{t("Open AI Model")}</label>
            <Select value={textData.config.model} onValueChange={(value) => handleInputChange("model", value)}>
              <SelectTrigger className="w-full bg-gray-50 border-gray-200">
                <SelectValue placeholder="Select Model" />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(settingConfig.text_ai.providers.openai.models).map(([value, label]) => (
                  <SelectItem key={value} value={value}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="col-span-1">
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-gray-200 mb-2">{t("Default Creativity Level")}</label>
            <Select
              value={textData.config.default_creativity}
              onValueChange={(value) => handleInputChange("default_creativity", value)}
            >
              <SelectTrigger className="w-full bg-gray-50 border-gray-200">
                <SelectValue placeholder="Select Creativy" />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(settingConfig.text_ai.settings.default_creativity).map(([value, label]) => (
                  <SelectItem key={value} value={value}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* Second Row - Select Fields (Half Width) */}
        <div className="grid lg:grid-cols-2 grid-cols-1 lg:gap-6 gap-4">
          <div className="col-span-1">
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-gray-200 mb-2">{t("Default Tone")}</label>
            <Select value={textData.config.default_tone} onValueChange={(value) => handleInputChange("default_tone", value)}>
              <SelectTrigger className="w-full bg-gray-50 border-gray-200">
                <SelectValue placeholder="Select Tone" />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(settingConfig.text_ai.settings.default_tone).map(([value, label]) => (
                  <SelectItem key={value} value={value}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="col-span-1">
            <label className="block text-sm font-medium text-bodyTextPrimary dark:text-gray-200 mb-2">{t("Default Max Result Length")}</label>
            <Input
              type="number"
              placeholder="150"
              value={textData.config.max_result}
              onChange={(e) => handleInputChange("max_result", e.target.value)}
              className="w-full bg-gray-50 border-gray-200"
            />
          </div>
        </div>

        {/* Third Row - Bad Words (Full Width) */}
        <div>
          <label className="block text-sm font-medium text-bodyTextPrimary dark:text-gray-200 mb-2">{t("Bad Words")}</label>
          <RSelectCreatable
            isMulti
            placeholder="Type bad words and press Enter..."
            options={textData.config.bad_words.map((word) => ({
              label: word,
              value: word
            }))}
            value={textData.config.bad_words}
            onChange={(newWords) => handleInputChange("bad_words", newWords)}
          />
        </div>

        {/* Fourth Row - API Key (Less than full width with button) */}
        <div>
          <label className="block text-sm font-medium text-bodyTextPrimary dark:text-gray-200 mb-2">{t("API Key")}</label>
          <div className="flex gap-4 items-end">
            <div className="flex-1 max-w-xxl">
              <Input
                type="text"
                placeholder="API Key"
                value={textData.config.api_key}
                onChange={(e) => handleInputChange("api_key", e.target.value)}
                className="w-full bg-gray-50 border-gray-200"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
