"use client"
import { useState, useEffect, forwardRef, useImperativeHandle } from "react"
import axios from "axios"
import { Site } from "@/app/types"
import { PencilLine, Building2, FileText } from "lucide-react"
import ErrorToast from "@/components/Error"
import SuccessToast from "@/components/Success"
import useSite from "@/hooks/useSites"

interface EditSiteProps {
  site: Site
  onSiteEdited?: () => void
}

const EditSite = forwardRef<{ resetForm: () => void }, EditSiteProps>(({ site, onSiteEdited }, ref) => {
  const [name, setName] = useState(site.name)
  const [description, setDescription] = useState(site.description || "")
  const [error, setError] = useState("")
  const [success, setSuccess] = useState("")
  const { editSite } = useSite()

  const resetForm = () => {
    setName(site.name)
    setDescription(site.description || "")
  }

  useImperativeHandle(ref, () => ({
    resetForm
  }))

  useEffect(() => {
    resetForm()
  }, [site])

  const handleEditSite = async () => {
      const result = editSite({ id: site.id, name, description, networks: site.networks })
      
      if (typeof result === "string") {
        setError(result)
        return
      }
      
      try {
        const successMessage = await result
        if (onSiteEdited && successMessage) {
          onSiteEdited()
          setSuccess(successMessage)
        }
      } catch (apiError) {
        setError(typeof apiError === "string" ? apiError : "Failed to edit site")
      }
  }

  return (
    <div>
      <dialog id="edit_site" className="modal">
        <div className="modal-box w-11/12 max-w-3xl border-l-4 border-primary">
          <div className="flex items-center gap-3 mb-3">
            <div className="bg-primary text-primary-content rounded-full p-2 flex items-center justify-center">
              <PencilLine className="h-6 w-6" />
            </div>
            <h3 className="font-bold text-xl">Edit Site</h3>
          </div>
          
          <div className="bg-base-200 p-4 rounded-lg mb-4">
            <div className="space-y-4">
              <div className="form-control">
                <label className="label">
                  <div className="flex items-center gap-2">
                    <Building2 className="h-4 w-4 opacity-70" />
                    <span className="label-text font-medium">Site Name</span>
                  </div>
                </label>
                <input 
                  type="text" 
                  placeholder="Enter site name" 
                  className="input input-bordered w-full" 
                  value={name} 
                  onChange={(e) => setName(e.target.value)}
                />
              </div>

              <div className="form-control">
                <label className="label">
                  <div className="flex items-center gap-2">
                    <FileText className="h-4 w-4 opacity-70" />
                    <span className="label-text font-medium">Description</span>
                    <span className="ml-1 text-xs opacity-60">(optional)</span>
                  </div>
                </label>
                <textarea 
                  placeholder="Enter site description" 
                  className="textarea textarea-bordered w-full h-24" 
                  value={description} 
                  onChange={(e) => setDescription(e.target.value)}
                />
              </div>
            </div>
          </div>

          <div className="modal-action">
            <form method="dialog" className="flex gap-3 w-full justify-end">
              <button className="btn btn-outline" onClick={resetForm}>Cancel</button>
              <button 
                className="btn btn-primary" 
                onClick={handleEditSite}
                disabled={!name}
              >
                Save Changes
              </button>
            </form>
          </div>
        </div>
      </dialog>
      <ErrorToast message={error} show={error !== ''} onClose={() => setError('')} />
      <SuccessToast message={success} show={success !== ''} onClose={() => setSuccess('')} />
    </div>
  )
})

EditSite.displayName = 'EditSite'

export default EditSite