import { useState } from 'react'
import { useShareToken, type SharePermission } from './useShareToken.ts'
import '../styles/share-dialog.css'

interface ShareDialogProps {
  documentId: string
  documentTitle: string
  currentShareToken: string | null
  currentSharePermission: string | null
  onClose: () => void
}

export function ShareDialog({
  documentId,
  documentTitle,
  currentShareToken,
  currentSharePermission,
  onClose,
}: ShareDialogProps) {
  const { createShareLink, revokeShareLink } = useShareToken()
  const [permission, setPermission] = useState<SharePermission>(
    (currentSharePermission as SharePermission) ?? 'view',
  )
  const [shareUrl, setShareUrl] = useState<string | null>(
    currentShareToken ? `${window.location.origin}/s/${currentShareToken}` : null,
  )
  const [loading, setLoading] = useState(false)
  const [copied, setCopied] = useState(false)

  const handleCreateLink = async () => {
    setLoading(true)
    const result = await createShareLink(documentId, permission)
    if (result) {
      setShareUrl(result.url)
    }
    setLoading(false)
  }

  const handleRevokeLink = async () => {
    setLoading(true)
    await revokeShareLink(documentId)
    setShareUrl(null)
    setLoading(false)
  }

  const handleCopy = async () => {
    if (!shareUrl) return
    await navigator.clipboard.writeText(shareUrl)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <div className="share-backdrop" onClick={onClose}>
      <div className="share-dialog" onClick={e => e.stopPropagation()}>
        <h2>Share "{documentTitle}"</h2>
        <button className="share-close" onClick={onClose}>&times;</button>

        <div className="share-permission">
          <label>Permission</label>
          <div className="share-permission-options">
            <button
              className={`share-perm-btn ${permission === 'view' ? 'active' : ''}`}
              onClick={() => setPermission('view')}
            >
              View only
            </button>
            <button
              className={`share-perm-btn ${permission === 'edit' ? 'active' : ''}`}
              onClick={() => setPermission('edit')}
            >
              Can edit
            </button>
          </div>
        </div>

        {shareUrl ? (
          <div className="share-link-section">
            <div className="share-link-row">
              <input
                className="share-link-input"
                value={shareUrl}
                readOnly
                onClick={e => (e.target as HTMLInputElement).select()}
              />
              <button className="share-copy-btn" onClick={handleCopy}>
                {copied ? 'Copied!' : 'Copy'}
              </button>
            </div>
            <button
              className="share-revoke-btn"
              onClick={handleRevokeLink}
              disabled={loading}
            >
              Revoke link
            </button>
          </div>
        ) : (
          <button
            className="share-create-btn"
            onClick={handleCreateLink}
            disabled={loading}
          >
            {loading ? 'Creating...' : 'Create share link'}
          </button>
        )}
      </div>
    </div>
  )
}
