"use client"

import { useState } from "react"
import { Input } from "@/Components/UI/Input"
import { Button } from "@/Components/UI/Button"
import { X, Plus } from "lucide-react"
import useTranslate from "@/hooks/useTranslate";
import { router, usePage } from "@inertiajs/react"

export default function Local() {
  const { props } = usePage();
  const site_settings = props?.site_settings
  const [isLocalEnabled, setIsLocalEnabled] = useState(

    site_settings?.local_storage === 1 || site_settings?.local_storage === "1"
  )
  const [selectedFileTypes, setSelectedFileTypes] = useState(["jpg", "png", "jpeg", "mp4"])
  const [showFileTypeDropdown, setShowFileTypeDropdown] = useState(false)
  const [formData, setFormData] = useState({
    maximum_file_upload: site_settings?.maximum_file_upload,
    max_file_upload: site_settings?.max_file_upload,
  })

  const [isSubmitting, setIsSubmitting] = useState(false)

  const t = useTranslate()

  const availableFileTypes = ["jpg", "png", "jpeg", "gif", "webp", "mp4", "avi", "mov", "pdf", "doc", "docx", "txt"]

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

  const addFileType = (fileType) => {
    if (!selectedFileTypes.includes(fileType)) {
      setSelectedFileTypes((prev) => [...prev, fileType])
    }
    setShowFileTypeDropdown(false)
  }

  const removeFileType = (fileType) => {
    setSelectedFileTypes((prev) => prev.filter((type) => type !== fileType))
  }

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

    router.post(route('user.setting.store'), {
      local_storage: isLocalEnabled ? "1" : "0",
      mime_types: selectedFileTypes,
      ...formData,
    }, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })
  }

  const unselectedFileTypes = availableFileTypes.filter((type) => !selectedFileTypes.includes(type))

  return (
    <div className="space-y-8">
      {/* Local Toggle */}
      <div className="space-y-4">
        <h3 className="text-lg font-medium text-gray-900 dark:text-neutral-200">{t("Local")}</h3>
        <div className="flex items-center space-x-3">
          <button
            onClick={() => setIsLocalEnabled(!isLocalEnabled)}
            className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:ring-offset-2 ${isLocalEnabled ? "bg-cyan-400" : "bg-gray-200"
              }`}
          >
            <span
              className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${isLocalEnabled ? "translate-x-6" : "translate-x-1"
                }`}
            />
          </button>
          <span className="text-sm text-gray-700 dark:text-neutral-200">{t("Local")}</span>
        </div>
      </div>

      {/* Supported File Types - Professional Tag Input */}
      <div className="space-y-4">
        <label className="block text-sm font-medium text-gray-700 dark:text-neutral-200">{t("Supported File Type")}</label>

        <div className="min-h-[42px] p-3 bg-gray-50 dark:bg-zinc-900 border border-gray-200 rounded-md focus-within:ring-2 focus-within:ring-cyan-500 focus-within:border-primary">
          <div className="flex flex-wrap gap-2 items-center">
            {/* Selected file type tags */}
            {selectedFileTypes.map((type) => (
              <span
                key={type}
                className="inline-flex items-center gap-1 px-2.5 py-1 bg-white dark:bg-zinc-900 border border-gray-200 text-gray-700 dark:text-neutral-200 text-sm rounded-md shadow-sm"
              >
                {type}
                <button
                  onClick={() => removeFileType(type)}
                  className="text-gray-400 hover:text-gray-600 transition-colors"
                >
                  <X size={14} />
                </button>
              </span>
            ))}

            {/* Add new file type button */}
            {unselectedFileTypes.length > 0 && (
              <div className="relative">
                <button
                  onClick={() => setShowFileTypeDropdown(!showFileTypeDropdown)}
                  className="inline-flex items-center gap-1 px-2.5 py-1 text-gray-500 hover:text-gray-700 dark:text-neutral-200 text-sm border border-dashed border-gray-300 hover:border-gray-400 rounded-md transition-colors"
                >
                  <Plus size={14} />
                  {t("Add type")}
                </button>

                {/* Dropdown for available file types */}
                {showFileTypeDropdown && (
                  <div className="absolute top-full left-0 mt-1 w-48 bg-white dark:bg-zinc-900 border border-gray-200 rounded-md shadow-lg z-10">
                    <div className="py-1 max-h-48 overflow-y-auto">
                      {unselectedFileTypes.map((type) => (
                        <button
                          key={type}
                          onClick={() => addFileType(type)}
                          className="w-full text-left px-3 py-2 text-sm text-gray-700 dark:text-neutral-200 hover:bg-gray-50 transition-colors"
                        >
                          {type}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* File Upload Limits */}
      <div className="grid lg:grid-cols-2 grid-cols-1 lg:gap-6 gap-4">
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-700 dark:text-neutral-200">{t("Maximum File Upload")}</label>
          <Input
            type="text"
            placeholder="Enter maximum files allowed (e.g., 100)"
            value={formData.maximum_file_upload}
            onChange={(e) => handleInputChange("maximum_file_upload", e.target.value)}
            className="bg-gray-50 border-gray-200"
          />
        </div>
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-700 dark:text-neutral-200">{t("Max File Upload (MB)")}</label>
          <Input
            type="text"
            placeholder="Enter max file size in MB (e.g., 10)"
            value={formData.max_file_upload}
            onChange={(e) => handleInputChange("max_file_upload", e.target.value)}
            className="bg-gray-50 border-gray-200"
          />
        </div>
      </div>

      {/* Submit Button */}
      <div className="pt-4">
        <Button
          isLoading={isSubmitting}
          onClick={handleSubmit}
          className="bg-cyan-400 hover:bg-cyan-500 text-white px-8 py-2.5 rounded-md font-medium"
        >
          {isSubmitting ? t("Submitting.. ") : t("Submit")}
        </Button>
      </div>
    </div>
  )
}
