"use client"

import { useState } from "react"
import { Copy, Check } from "lucide-react"
import { Button } from "@/Components/UI/Button"
import AppLayout from "@/Layouts/AppLayout"
import { Input } from "@/Components/UI/Input"
import { route } from "ziggy-js"
import { router } from "@inertiajs/react"
import useTranslate from "@/hooks/useTranslate";
import PlatformIcon from "@/Components/UI/PlatformIcon"
import {  ArrowLeft } from "lucide-react"

export default function PlatformSetting({ platform = { name: "Platform", configuration: {} } , dynamicFields }) {
  const breadcrumbs = [
    { label: "Home", href: route("user.home") },
    { label: "Platform", href: route("user.platform.index") },
    { label: `${platform.name} Settings`, href: "#" },
  ]

  const [formData, setFormData] = useState(platform.configuration || {})
  const [copiedField, setCopiedField] = useState(null)
  const [isSubmitting, setIsSubmitting] = useState(false)


  const formatLabel = (key) => {
    return key
      .split("_")
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(" ")
  }

  const isUrlField = (key, value) => {
    return key.toLowerCase().includes("url") || (typeof value === "string" && value.startsWith("http"))
  }

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

  const handleCopy = async (value, fieldKey) => {
    try {
      await navigator.clipboard.writeText(value)
      setCopiedField(fieldKey)
      setTimeout(() => setCopiedField(null), 2000)
    } catch (err) {
      console.error("Failed to copy:", err)
    }
  }

  // Handle form submission
  const handleSubmit = (e) => {
    e.preventDefault()
    setIsSubmitting(true)

    router.post(route('user.platform.setting.store'), { id: platform.id, configuration: formData }, {
      onFinish: () => setIsSubmitting(false),
      onError: () => setIsSubmitting(false),
    })


  }

  return (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="p-6 space-y-6 min-h-full">
        {/* Header */}
        <div className="mb-6">
          <div className="flex items-center gap-4 mb-4">
              <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => router.get(route("user.platform.index"))}
                  className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
              >
                  <ArrowLeft className="w-4 h-4 mr-2" />
                  Back to Platforms
              </Button>
          </div>
          <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-4">
                  <div>
                      <PlatformIcon slug={platform.slug} size={32} />
                  </div>
                  <div>
                      <h1 className="text-xl sm:text-2xl font-bold text-gray-900 dark:text-gray-100">
                          {platform.name} API Settings
                      </h1>
                      <p className="text-gray-600 dark:text-gray-400">
                          Manage your {platform.name} API settings and connections
                      </p>
                  </div>
              </div> 
          </div> 
        </div>

        {/* Configuration Form */}
        <div className="bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800 lg:p-6 p-4">
          <h2 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-6">Update Configuration</h2>

          <form onSubmit={handleSubmit} className="space-y-8">
            {/* Dynamic Fields Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {Object.entries(formData).map(([key, value]) => (
                <div key={key} className="space-y-2">
                  <label className="block text-sm font-medium text-gray-700 dark:text-zinc-100">{formatLabel(key)}</label>

                  <div className="relative">
                    <Input
                      type="text"
                      value={value || ""}
                      onChange={(e) => handleInputChange(key, e.target.value)}
                      placeholder="Enter configuration value"
                      className="bg-gray-50 border-gray-200 pr-10"
                    />

                    {/* Copy button for URL fields */}
                    {isUrlField(key, value) && value && (
                      <button
                        type="button"
                        onClick={() => handleCopy(value, key)}
                        className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 transition-colors"
                      >
                        {copiedField === key ? (
                          <Check className="h-4 w-4 text-green-500" />
                        ) : (
                          <Copy className="h-4 w-4" />
                        )}
                      </button>
                    )}
                  </div>

                  <p className="text-sm text-gray-500">
                    Enter the {formatLabel(key).toLowerCase()} for your {platform.name.toLowerCase()} integration.
                  </p>
                </div>
              ))}

              {/* Dynamic read-only fields */}
              {Object.entries(dynamicFields).map(([key, value]) => (
                <div key={key} className="space-y-2">
                  <label className="block text-sm font-medium text-gray-700 dark:text-zinc-100">{formatLabel(key)}</label>
                  <div className="relative">
                    <Input
                      type="text"
                      value={value}
                      readOnly
                      className="bg-gray-100 pr-10 cursor-text"
                    />
                    <button
                      type="button"
                      onClick={() => handleCopy(value, key)}
                      className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-600 transition-colors"
                    >
                      {copiedField === key ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}
                    </button>
                  </div>
                  <p className="text-sm text-gray-500">
                    Use this URL for your {platform.name.toLowerCase()} integration.
                  </p>
                </div>
              ))}
            </div>

            {/* Action Buttons */}
            <div className="flex items-center gap-4 pt-4">
              <Button
                type="submit"
                disabled={isSubmitting}
                className="bg-gradient-to-r from-primary to-secondary text-white px-8 py-2 hover:from-secondary hover:to-primary"
              >
                {isSubmitting ? "Updating..." : "Update"}
              </Button>
            </div>
          </form>
        </div>
      </div>
    </AppLayout>
  )
}
