"use client"
import Sidebar from "@/components/Sidebar"
import useSite from "@/hooks/useSites"
import { useEffect, useState, useRef } from "react"
import { Network } from "@/app/types"
import Loading from "@/components/Loading"
import { EditModeToggle } from "@/components/EditModeToggle"
import AddNetwork from "@/components/dialogues/AddNetwork"
import { Plus, Pencil, Trash, Info, Cpu } from "lucide-react"
import EditNetwork from "@/components/dialogues/EditNetwork"
import DeleteNetwork from "@/components/dialogues/DeleteNetwork"
import EditSite from "@/components/dialogues/EditSite"
import DeleteSite from "@/components/dialogues/DeleteSite"

interface SitesPageProps {
  username: string
  name: string
  siteId: number
}

export default function SitesPage({ username, name, siteId }: SitesPageProps) {
  const { site, loadSite, updateSite, setSiteId, loading } = useSite()
  const [isEditMode, setIsEditMode] = useState(false)
  const editSiteRef = useRef<{ resetForm: () => void }>(null)
  
  const [selectedNetwork, setSelectedNetwork] = useState<Network | null>(null)
  const [selectedNetworkId, setSelectedNetworkId] = useState<number | null>(null)

  useEffect(() => {
    if (siteId) {
      setSiteId(siteId)
    }
  }, [siteId, setSiteId])

  const handleEditClick = () => {
    editSiteRef.current?.resetForm()
    ;(document.getElementById('edit_site') as HTMLDialogElement)?.showModal()
  }

  return (
    <Sidebar username={username} fullName={name} breadcrumbPath={["/", "Dashboard", "Resources", "Sites", site.name]}>
      <main className="w-full">
        {loading ? (
          <div className="flex justify-center items-center h-64 w-full">
            <Loading />
          </div>
        ) : (
        <div className="flex flex-col gap-4 w-full">
          <div className="card bg-base-100 shadow-xl rounded-xl overflow-hidden border border-base-200 w-full">
            <div className="card-body p-6">
              <div className="w-full flex justify-between items-center mb-4">
                <h1 className="text-2xl font-bold">Site - {site.name}</h1>
                <div className="flex items-center gap-2">
                  {isEditMode && (
                    <>
                      <button 
                        className="btn btn-primary btn-sm px-2" 
                        onClick={handleEditClick}
                      >
                        <Pencil className="h-4 w-4" />
                      </button>
                      <button 
                        className="btn btn-error btn-sm px-2" 
                        onClick={() => (document.getElementById('delete_site') as HTMLDialogElement)?.showModal()}
                      >
                        <Trash className="h-4 w-4" />
                      </button>
                    </>
                  )}
                  <EditModeToggle toggle={setIsEditMode} isActive={isEditMode} />
                </div>
              </div>
              
              <div className="bg-base-200 p-4 rounded-xl mb-2">
                <h2 className="text-sm font-semibold mb-1 flex items-center gap-1.5">
                  <Info className="h-4 w-4 opacity-70" />
                  Description
                </h2>
                <p className="text-sm">
                  {site.description || "No description provided for this site."}
                </p>
              </div>
            </div>
          </div>

          <div className="card bg-base-100 shadow-xl rounded-xl overflow-hidden border border-base-200 w-full">
            <div className="card-body p-6">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-xl font-bold">Networks</h2>
                {isEditMode && (
                  <button 
                    className="btn btn-primary btn-sm px-2" 
                    onClick={() => (document.getElementById('add_network') as HTMLDialogElement)?.showModal()}
                  >
                    <Plus className="w-5 h-5" />
                  </button>
                )}
              </div>

              {site.networks && site.networks.length > 0 ? (
                <div className="rounded-xl overflow-hidden border border-base-200">
                  <div className="overflow-x-auto">
                    <table className="table table-zebra">
                      <thead className="bg-base-200 text-base-content">
                        <tr>
                          <th className="w-12 text-center">#</th>
                          <th>Network Name</th>
                          <th>IPv4 Subnet</th>
                          <th>IPv6 Subnet</th>
                          <th>Gateway</th>
                          {isEditMode && <th className="w-24 text-center">Actions</th>}
                        </tr>
                      </thead>
                      <tbody>
                        {site.networks.map((network, index) => (
                          <tr key={index} className="hover:bg-base-200/50">
                            <th className="text-center font-normal text-base-content/70">{index + 1}</th>
                            <td className="font-medium">{network.name}</td>
                            <td className="font-mono text-xs">{network.ipv4Subnet || "—"}</td>
                            <td className="font-mono text-xs">{network.ipv6Subnet || "—"}</td>
                            <td className="font-mono text-xs">{network.gateway || "—"}</td>
                            {isEditMode && (
                              <td className="px-0">
                                <div className="flex gap-1 justify-center">
                                  <button 
                                    className="btn btn-primary btn-s px-2" 
                                    onClick={() => {
                                      setSelectedNetwork(network);
                                      (document.getElementById('edit_network') as HTMLDialogElement)?.showModal();
                                    }}
                                  >
                                    <Pencil className="h-3 w-3" />
                                  </button>
                                  <button 
                                    className="btn btn-error btn-s px-2" 
                                    onClick={() => {
                                      setSelectedNetworkId(network.id);
                                      (document.getElementById('delete_network') as HTMLDialogElement)?.showModal();
                                    }}
                                  >
                                    <Trash className="h-3 w-3" />
                                  </button>
                                </div>
                              </td>
                            )}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-12 bg-base-200 rounded-xl">
                  <div className="bg-base-100 p-4 rounded-full mb-4">
                    <Cpu className="h-8 w-8 text-base-content/50" />
                  </div>
                  <p className="text-base-content/70 mb-4">No networks have been added to this site yet.</p>
                  {isEditMode && (
                    <button 
                      className="btn btn-primary btn-sm gap-2" 
                      onClick={() => (document.getElementById('add_network') as HTMLDialogElement)?.showModal()}
                    >
                      <Plus className="h-4 w-4" />
                      Add Your First Network
                    </button>
                  )}
                </div>
              )}
            </div>
          </div>
          
        </div>
        )}

        <AddNetwork siteId={site.id} onNetworkAdded={updateSite}/>
        <EditSite ref={editSiteRef} site={site} onSiteEdited={updateSite} />
        <DeleteSite siteId={site.id} />
        {selectedNetwork && (
          <EditNetwork 
            siteId={site.id} 
            network={selectedNetwork} 
            onNetworkEdited={updateSite} 
          />
        )}
        {selectedNetworkId && (
          <DeleteNetwork 
            networkId={selectedNetworkId} 
            onNetworkDeleted={updateSite} 
          />
        )}
      </main>
    </Sidebar>
  )
}