import { useState, useCallback, useRef } from 'react'
import { Upload, FileText, ClipboardPaste, FileUp, Sparkles, AlertCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Textarea } from '@/components/ui/Textarea'
import { Input } from '@/components/ui/Input'
import type { KBQuotaResponse } from '@/types/kbAccelerator'

type TargetType = 'troubleshooting' | 'procedural'

interface UploadScreenProps {
  quota: KBQuotaResponse | null
  onSubmitText: (content: string, title: string, targetType: TargetType) => void
  onSubmitFile: (file: File, targetType: TargetType) => void
  loading: boolean
}

const TARGET_TYPES = [
  {
    value: 'troubleshooting' as const,
    label: 'Troubleshooting Flow',
    description: 'Decision tree with diagnostic questions and resolutions',
  },
  {
    value: 'procedural' as const,
    label: 'Project Flow',
    description: 'Step-by-step procedure with warnings and variables',
  },
]

const FORMAT_LABELS: Record<string, string> = {
  txt: 'TXT',
  paste: 'Paste',
  docx: 'DOCX',
  pdf: 'PDF',
  html: 'HTML',
  md: 'Markdown',
}

export function UploadScreen({ quota, onSubmitText, onSubmitFile, loading }: UploadScreenProps) {
  const [mode, setMode] = useState<'paste' | 'file'>('paste')
  const [content, setContent] = useState('')
  const [title, setTitle] = useState('')
  const [targetType, setTargetType] = useState<TargetType>('troubleshooting')
  const [file, setFile] = useState<File | null>(null)
  const [dragOver, setDragOver] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const canSubmit = mode === 'paste'
    ? content.trim().length >= 10
    : file !== null

  const handleSubmit = () => {
    if (loading) return
    if (mode === 'paste') {
      onSubmitText(content, title, targetType)
    } else if (file) {
      onSubmitFile(file, targetType)
    }
  }

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
    const droppedFile = e.dataTransfer.files[0]
    if (droppedFile) {
      setFile(droppedFile)
      setMode('file')
    }
  }, [])

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files?.[0]
    if (selected) {
      setFile(selected)
    }
  }

  const allowedFormats = quota?.allowed_formats ?? ['txt', 'paste']
  const fileFormats = allowedFormats.filter(f => f !== 'paste')

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      {/* Quota info */}
      {quota && (
        <div className="card-flat p-4 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Sparkles size={18} className="text-primary" />
            <div>
              <p className="text-sm font-medium text-foreground">
                {quota.lifetime_conversions_limit
                  ? `${quota.lifetime_conversions_limit - quota.lifetime_conversions_used} conversions remaining`
                  : 'Unlimited conversions'}
              </p>
              <p className="text-xs text-muted-foreground">
                {quota.plan.charAt(0).toUpperCase() + quota.plan.slice(1)} plan
              </p>
            </div>
          </div>
          {!quota.can_convert && (
            <div className="flex items-center gap-2 text-amber-400 text-sm">
              <AlertCircle size={16} />
              <span>Conversion limit reached</span>
            </div>
          )}
        </div>
      )}

      {/* Mode toggle */}
      <div className="flex gap-2">
        <button
          onClick={() => setMode('paste')}
          className={cn(
            'flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors',
            mode === 'paste'
              ? 'bg-accent-dim text-foreground border border-primary/30'
              : 'bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] text-muted-foreground hover:text-foreground hover:border-[rgba(255,255,255,0.12)]'
          )}
        >
          <ClipboardPaste size={16} />
          Paste Text
        </button>
        {fileFormats.length > 0 && (
          <button
            onClick={() => setMode('file')}
            className={cn(
              'flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors',
              mode === 'file'
                ? 'bg-accent-dim text-foreground border border-primary/30'
                : 'bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] text-muted-foreground hover:text-foreground hover:border-[rgba(255,255,255,0.12)]'
            )}
          >
            <FileUp size={16} />
            Upload File
          </button>
        )}
      </div>

      {/* Content area */}
      <div className="card-flat p-5 space-y-4">
        {mode === 'paste' ? (
          <>
            <div>
              <label htmlFor="kb-title" className="block font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-1.5">
                Title (optional)
              </label>
              <Input
                id="kb-title"
                value={title}
                onChange={e => setTitle(e.target.value)}
                placeholder="e.g., Outlook Connectivity Troubleshooting"
                maxLength={255}
              />
            </div>
            <div>
              <label htmlFor="kb-content" className="block font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-1.5">
                KB Article Content
              </label>
              <Textarea
                id="kb-content"
                value={content}
                onChange={e => setContent(e.target.value)}
                placeholder="Paste your KB article text here..."
                rows={12}
                maxLength={500000}
              />
              <p className="mt-1 text-xs text-muted-foreground">
                {content.length.toLocaleString()} / 500,000 characters
              </p>
            </div>
          </>
        ) : (
          <div
            onDragOver={e => { e.preventDefault(); setDragOver(true) }}
            onDragLeave={() => setDragOver(false)}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current?.click()}
            className={cn(
              'flex flex-col items-center justify-center gap-3 p-10 rounded-xl border-2 border-dashed cursor-pointer transition-colors',
              dragOver
                ? 'border-primary/50 bg-primary/5'
                : 'border-[rgba(255,255,255,0.08)] hover:border-[rgba(255,255,255,0.15)]'
            )}
          >
            {file ? (
              <>
                <FileText size={32} className="text-primary" />
                <div className="text-center">
                  <p className="text-sm font-medium text-foreground">{file.name}</p>
                  <p className="text-xs text-muted-foreground mt-1">
                    {(file.size / 1024).toFixed(1)} KB
                  </p>
                  <button
                    onClick={e => { e.stopPropagation(); setFile(null) }}
                    className="mt-2 text-xs text-primary hover:underline"
                  >
                    Remove
                  </button>
                </div>
              </>
            ) : (
              <>
                <Upload size={32} className="text-muted-foreground" />
                <div className="text-center">
                  <p className="text-sm text-foreground">
                    Drop a file here or <span className="text-primary">browse</span>
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    Supported: {fileFormats.map(f => FORMAT_LABELS[f] || f.toUpperCase()).join(', ')}
                  </p>
                </div>
              </>
            )}
            <input
              ref={fileInputRef}
              type="file"
              className="hidden"
              accept={fileFormats.map(f => `.${f}`).join(',')}
              onChange={handleFileSelect}
            />
          </div>
        )}
      </div>

      {/* Target type selector */}
      <div>
        <p className="font-sans text-xs text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-2">
          Target Flow Type
        </p>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          {TARGET_TYPES.map(t => (
            <button
              key={t.value}
              onClick={() => setTargetType(t.value)}
              className={cn(
                'card-flat p-4 text-left transition-all',
                targetType === t.value
                  ? 'border-primary/30 bg-primary/5'
                  : 'hover:border-[rgba(255,255,255,0.12)]'
              )}
            >
              <p className="text-sm font-medium text-foreground">{t.label}</p>
              <p className="text-xs text-muted-foreground mt-1">{t.description}</p>
            </button>
          ))}
        </div>
      </div>

      {/* Submit */}
      <button
        onClick={handleSubmit}
        disabled={!canSubmit || loading || (quota != null && !quota.can_convert)}
        className={cn(
          'w-full flex items-center justify-center gap-2 px-6 py-3 rounded-lg text-sm font-semibold transition-all',
          'bg-primary text-white',
          'hover:brightness-110 active:scale-[0.98]',
          'disabled:opacity-50 disabled:cursor-not-allowed'
        )}
      >
        <Sparkles size={16} />
        {loading ? 'Converting...' : 'Convert to Flow'}
      </button>
    </div>
  )
}
