import { AuthService } from '../../../auth/authService.ts'
import { useEffect, useState, useRef, MouseEvent } from 'react'
import { SignupCode } from '../../../auth/signupCode.ts'
import { Temporal } from '@js-temporal/polyfill'
import Button from '../../../../components/buttons/Button.tsx'

interface SignupCodesManagementPageProps {
  authService: AuthService
}

export default function SignupCodesManagementPage({ authService }: SignupCodesManagementPageProps) {
  const [codes, setCodes] = useState<SignupCode[]>([])
  const [code, setCode] = useState('')
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const dialogRef = useRef<HTMLDialogElement>(null)
  const [tooltipPosition, setTooltipPosition] = useState<{ x: number; y: number } | null>(null)
  const [activeCode, setActiveCode] = useState<string | null>(null)

  const fetchCodes = async () => {
    try {
      setCodes(await authService.listSignupCodes())
    } catch (err) {
      console.error('Failed to fetch signup codes:', err)
    }
  }

  useEffect(() => {
    const timeoutId = setTimeout(fetchCodes)
    return () => clearTimeout(timeoutId)
  }, [authService])

  const handleCreateCode = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError(null)

    try {
      await authService.createSignupCode(code, email, name)
      setCode('')
      setName('')
      setEmail('')
      dialogRef.current?.close()
      fetchCodes() // Refresh the table
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create signup code')
    } finally {
      setIsLoading(false)
    }
  }

  const openDialog = () => {
    dialogRef.current?.showModal()
  }

  const closeDialog = () => {
    dialogRef.current?.close()
    setError(null)
  }

  const formatDate = (date: Temporal.Instant | null) => {
    if (!date) return 'Never'
    try {
      const jsDate = new Date(date.epochMilliseconds)

      // Format as: "Jan 1, 2023, 12:00 PM"
      return jsDate.toLocaleString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
      })
    } catch (err: unknown) {
      console.error(err)
      return date.toString()
    }
  }

  const copyCodeToClipboard = (code: string, e: MouseEvent) => {
    e.preventDefault()
    const host = window.location.origin
    const url = `${host}?c=${code}`
    navigator.clipboard.writeText(url)
      .then(() => {
        // Optional: Show a success message or notification
        console.log('Copied to clipboard:', url)
      })
      .catch(err => {
        console.error('Failed to copy:', err)
      })
    setTooltipPosition(null)
    setActiveCode(null)
  }

  const showTooltip = (code: string, e: MouseEvent) => {
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
    setTooltipPosition({ 
      x: rect.left + rect.width / 2, 
      y: rect.top - 10 
    })
    setActiveCode(code)
  }

  const hideTooltip = () => {
    setTooltipPosition(null)
    setActiveCode(null)
  }

  return (
    <>
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-xl font-bold">Signup Codes</h1>
        <Button onClick={openDialog}>Create New Code</Button>
      </div>

      <div className="overflow-x-auto">
        <table className="min-w-full bg-white">
          <thead>
            <tr>
              <th className="text-left">Code</th>
              <th className="text-left">Email</th>
              <th className="text-left">Redeemed By</th>
              <th className="text-left">Expires On</th>
            </tr>
          </thead>
          <tbody>
            {codes.map((code) => (
              <tr key={code.code} className="hover:bg-gray-50">
                <td className="py-2 ">
                  <button 
                    className="bg-primary-100 px-2 py-1 rounded font-mono text-sm cursor-pointer hover:bg-primary-200 transition-colors"
                    onClick={(e) => copyCodeToClipboard(code.code, e)}
                    onMouseEnter={(e) => showTooltip(code.code, e)}
                    onMouseLeave={hideTooltip}
                  >
                    {code.code}
                  </button>
                </td>
                <td>{code.email}</td>
                <td>{code.redeemedBy || 'Not redeemed'}</td>
                <td>{formatDate(code.expiresOn)}</td>
              </tr>
            ))}
            {codes.length === 0 && (
              <tr>
                <td colSpan={4} className="py-4 text-center text-gray-500">
                  No signup codes found
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <dialog
        ref={dialogRef}
        className="p-6 rounded-lg shadow-lg backdrop-blur-sm w-full max-w-md m-auto"
      >
        <h2 className="text-xl font-bold mb-4">Create New Signup Code</h2>

        {error && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            {error}
          </div>
        )}

        <form onSubmit={handleCreateCode}>
          <div className="mb-4">
            <label htmlFor="code" className="block text-sm font-medium text-gray-700 mb-1">
              Code ID
            </label>
            <input
              type="text"
              id="code"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md"
              required
            />
          </div>

          <div className="mb-4">
            <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
              Name
            </label>
            <input
              type="text"
              id="name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md"
              required
            />
          </div>

          <div className="mb-4">
            <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
              Email
            </label>
            <input
              type="email"
              id="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md"
              required
            />
          </div>

          <div className="flex justify-end space-x-2">
            <Button type="button" onClick={closeDialog} secondary>
              Cancel
            </Button>
            <Button type="submit" disabled={isLoading}>
              {isLoading ? 'Creating...' : 'Create Code'}
            </Button>
          </div>
        </form>
      </dialog>

      {tooltipPosition && activeCode && (
        <dialog 
          open
          className="fixed p-2 bg-gray-800 text-white text-xs rounded shadow-lg z-50"
          style={{
            left: `${tooltipPosition.x}px`,
            top: `${tooltipPosition.y}px`,
            transform: 'translate(-50%, -100%)',
            margin: 0,
            border: 'none',
          }}
        >
          Copy to clipboard
        </dialog>
      )}
    </>
  )
}
