import { useState, useEffect } from 'react'
import { Copy, Download, Check, RotateCcw } from 'lucide-react'
import { Modal } from '@/components/common/Modal'
import { cn } from '@/lib/utils'
import type { RedactionSummary } from '@/types'

interface ExportPreviewModalProps {
  isOpen: boolean
  onClose: () => void
  content: string
  filename: string
  format: 'markdown' | 'text' | 'html' | 'psa'
  onDownload: (content: string) => void
  includeSummary?: boolean
  onToggleSummary?: (include: boolean) => void
  redactionEnabled?: boolean
  onToggleRedaction?: (enabled: boolean) => void
  redactionSummary?: RedactionSummary | null
}

export function ExportPreviewModal({
  isOpen,
  onClose,
  content,
  filename,
  format,
  onDownload,
  includeSummary = false,
  onToggleSummary,
  redactionEnabled = false,
  onToggleRedaction,
  redactionSummary,
}: ExportPreviewModalProps) {
  const [copied, setCopied] = useState(false)
  const [editedContent, setEditedContent] = useState(content)

  // Sync editedContent when content prop changes (new fetch / summary toggle)
  useEffect(() => {
    setEditedContent(content)
  }, [content])

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(editedContent)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (err) {
      console.error('Failed to copy:', err)
    }
  }

  const handleDownload = () => {
    onDownload(editedContent)
    onClose()
  }

  const handleReset = () => {
    setEditedContent(content)
  }

  const handleClose = () => {
    setCopied(false)
    onClose()
  }

  const isModified = editedContent !== content

  return (
    <Modal isOpen={isOpen} onClose={handleClose} title="Export Preview" size="xl">
      {/* Filename, format info, and controls */}
      <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
        <p className="text-sm text-muted-foreground">
          Filename: <span className="font-mono text-foreground">{filename}</span>
          <span className="ml-3 rounded bg-accent px-2 py-0.5 text-xs text-muted-foreground">
            {format === 'markdown' ? 'Markdown' : format === 'html' ? 'HTML' : format === 'psa' ? 'PSA' : 'Plain Text'}
          </span>
          {isModified && (
            <span className="ml-2 text-xs text-yellow-400">(edited)</span>
          )}
        </p>
        <div className="flex flex-col items-end gap-1">
          <div className="flex items-center gap-3">
            {onToggleSummary && (
              <label className="flex items-center gap-2 text-sm text-muted-foreground cursor-pointer">
                <input
                  type="checkbox"
                  checked={includeSummary}
                  onChange={(e) => onToggleSummary(e.target.checked)}
                  className="h-4 w-4 rounded border-border bg-card"
                />
                Include Summary
              </label>
            )}
            {onToggleRedaction && (
              <label className="flex items-center gap-2 text-sm text-muted-foreground cursor-pointer">
                <input
                  type="checkbox"
                  checked={redactionEnabled}
                  onChange={(e) => onToggleRedaction(e.target.checked)}
                  className="h-4 w-4 rounded border-border bg-card"
                />
                Mask Sensitive Data
              </label>
            )}
          </div>
          {redactionEnabled && redactionSummary && redactionSummary.total > 0 && (
            <p className="text-xs text-blue-400">
              Masked: {[
                redactionSummary.ips > 0 && `${redactionSummary.ips} IP${redactionSummary.ips !== 1 ? 's' : ''}`,
                redactionSummary.emails > 0 && `${redactionSummary.emails} email${redactionSummary.emails !== 1 ? 's' : ''}`,
                redactionSummary.tokens > 0 && `${redactionSummary.tokens} token${redactionSummary.tokens !== 1 ? 's' : ''}`,
                redactionSummary.unc_paths > 0 && `${redactionSummary.unc_paths} UNC path${redactionSummary.unc_paths !== 1 ? 's' : ''}`,
              ].filter(Boolean).join(', ')}
            </p>
          )}
          {redactionEnabled && redactionSummary && redactionSummary.total === 0 && (
            <p className="text-xs text-muted-foreground">No sensitive data detected</p>
          )}
          {isModified && (
            <button
              type="button"
              onClick={handleReset}
              className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
              title="Reset to original"
            >
              <RotateCcw className="h-3 w-3" />
              Reset
            </button>
          )}
        </div>
      </div>

      {/* Editable Content */}
      <label htmlFor="export-content" className="sr-only">
        Export content
      </label>
      <textarea
        id="export-content"
        value={editedContent}
        onChange={(e) => setEditedContent(e.target.value)}
        className={cn(
          'h-96 w-full resize-y rounded-md border border-border bg-card p-4',
          'font-mono text-sm text-foreground',
          'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20'
        )}
      />

      {/* Actions */}
      <div className="mt-4 flex items-center justify-end gap-2">
        <button
          type="button"
          onClick={handleCopy}
          className={cn(
            'flex items-center gap-2 rounded-md border border-border px-3 py-2 text-sm font-medium',
            'text-muted-foreground hover:bg-accent hover:text-foreground',
            'focus:outline-none focus:ring-2 focus:ring-primary/20'
          )}
        >
          {copied ? (
            <>
              <Check className="h-4 w-4 text-emerald-400" />
              Copied!
            </>
          ) : (
            <>
              <Copy className="h-4 w-4" />
              Copy to Clipboard
            </>
          )}
        </button>
        <button
          type="button"
          onClick={handleDownload}
          className={cn(
            'flex items-center gap-2 rounded-md bg-gradient-brand text-white shadow-lg shadow-primary/20 px-3 py-2 text-sm font-medium',
            'hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-primary/20'
          )}
        >
          <Download className="h-4 w-4" />
          Download
        </button>
      </div>
    </Modal>
  )
}

export default ExportPreviewModal
