import { useState, useEffect } from 'react'
import {
  X,
  CheckCircle2,
  ArrowUpRight,
  Pause,
  Loader2,
  Copy,
  Check,
  RefreshCw,
  ClipboardList,
  Sparkles,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { MarkdownContent } from '@/components/ui/MarkdownContent'

type ConclusionOutcome = 'resolved' | 'escalated' | 'paused'

interface ConcludeSessionModalProps {
  isOpen: boolean
  onClose: () => void
  onConclude: (outcome: ConclusionOutcome, notes: string) => Promise<string>
  onResumeNew: (summary: string) => void
  chatTitle: string
}

const OUTCOMES: { value: ConclusionOutcome; label: string; description: string; icon: typeof CheckCircle2; color: string; bg: string; border: string }[] = [
  {
    value: 'resolved',
    label: 'Resolved',
    description: 'Issue has been fixed or answered',
    icon: CheckCircle2,
    color: 'text-emerald-400',
    bg: 'bg-emerald-400/10',
    border: 'border-emerald-400/30',
  },
  {
    value: 'escalated',
    label: 'Escalate',
    description: 'Needs to be handed off or escalated',
    icon: ArrowUpRight,
    color: 'text-amber-400',
    bg: 'bg-amber-400/10',
    border: 'border-amber-400/30',
  },
  {
    value: 'paused',
    label: 'Paused',
    description: 'Continuing later — saving progress',
    icon: Pause,
    color: 'text-blue-400',
    bg: 'bg-blue-400/10',
    border: 'border-blue-400/30',
  },
]

type ModalStep = 'select-outcome' | 'add-notes' | 'summary'

export function ConcludeSessionModal({
  isOpen,
  onClose,
  onConclude,
  onResumeNew,
  chatTitle,
}: ConcludeSessionModalProps) {
  const [step, setStep] = useState<ModalStep>('select-outcome')
  const [outcome, setOutcome] = useState<ConclusionOutcome | null>(null)
  const [notes, setNotes] = useState('')
  const [summary, setSummary] = useState('')
  const [generating, setGenerating] = useState(false)
  const [copied, setCopied] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Reset state when modal opens
  useEffect(() => {
    if (isOpen) {
      setStep('select-outcome')
      setOutcome(null)
      setNotes('')
      setSummary('')
      setGenerating(false)
      setCopied(false)
      setError(null)
    }
  }, [isOpen])

  const handleOutcomeSelect = (selected: ConclusionOutcome) => {
    setOutcome(selected)
    setStep('add-notes')
  }

  const handleGenerate = async () => {
    if (!outcome) return
    setGenerating(true)
    setError(null)

    try {
      const result = await onConclude(outcome, notes)
      setSummary(result)
      setStep('summary')
    } catch {
      setError('Failed to generate summary. Please try again.')
    } finally {
      setGenerating(false)
    }
  }

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(summary)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch {
      // Fallback
      const textarea = document.createElement('textarea')
      textarea.value = summary
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }

  const handleResumeNew = () => {
    onResumeNew(summary)
    onClose()
  }

  if (!isOpen) return null

  const selectedOutcome = OUTCOMES.find(o => o.value === outcome)

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-xs"
        onClick={onClose}
      />

      {/* Modal */}
      <div
        className="relative w-full max-w-2xl mx-4 glass-card-static overflow-hidden animate-in fade-in zoom-in-95 duration-200"
        style={{
          maxHeight: 'calc(100vh - 4rem)',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        {/* Header */}
        <div
          className="flex items-center justify-between px-6 py-4 border-b shrink-0"
          style={{ borderColor: 'var(--glass-border)' }}
        >
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center">
              <ClipboardList size={18} className="text-primary" />
            </div>
            <div>
              <h2 className="text-base font-heading font-semibold text-foreground">
                Conclude Session
              </h2>
              <p className="text-xs text-muted-foreground truncate max-w-[300px]">
                {chatTitle}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-brand-border text-muted-foreground hover:text-foreground transition-colors"
          >
            <X size={18} />
          </button>
        </div>

        {/* Step indicator */}
        <div
          className="px-6 py-3 border-b shrink-0 flex items-center gap-2"
          style={{ borderColor: 'var(--glass-border)' }}
        >
          {(['select-outcome', 'add-notes', 'summary'] as ModalStep[]).map((s, i) => (
            <div key={s} className="flex items-center gap-2">
              {i > 0 && (
                <div
                  className={cn(
                    'w-8 h-px',
                    step === s || (i === 1 && step === 'summary') || (i === 2 && step === 'summary')
                      ? 'bg-primary/40'
                      : 'bg-brand-border'
                  )}
                />
              )}
              <div
                className={cn(
                  'w-6 h-6 rounded-full flex items-center justify-center text-[0.6875rem] font-label font-medium transition-colors',
                  step === s
                    ? 'bg-gradient-brand text-brand-dark'
                    : (i < ['select-outcome', 'add-notes', 'summary'].indexOf(step))
                    ? 'bg-primary/20 text-primary'
                    : 'bg-brand-border text-muted-foreground'
                )}
              >
                {i + 1}
              </div>
              <span
                className={cn(
                  'text-xs font-label',
                  step === s ? 'text-foreground' : 'text-muted-foreground'
                )}
              >
                {s === 'select-outcome' ? 'Outcome' : s === 'add-notes' ? 'Notes' : 'Summary'}
              </span>
            </div>
          ))}
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto px-6 py-5">
          {/* Step 1: Select Outcome */}
          {step === 'select-outcome' && (
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground mb-4">
                How did this session end?
              </p>
              {OUTCOMES.map(o => {
                const Icon = o.icon
                return (
                  <button
                    key={o.value}
                    onClick={() => handleOutcomeSelect(o.value)}
                    className={cn(
                      'w-full flex items-center gap-4 p-4 rounded-xl border transition-all text-left',
                      'hover:scale-[1.01] active:scale-[0.99]',
                      'bg-[rgba(255,255,255,0.02)] border-brand-border',
                      'hover:border-[rgba(255,255,255,0.12)] hover:bg-[rgba(255,255,255,0.04)]'
                    )}
                  >
                    <div className={cn('w-10 h-10 rounded-xl flex items-center justify-center', o.bg)}>
                      <Icon size={20} className={o.color} />
                    </div>
                    <div>
                      <span className="text-sm font-semibold text-foreground block">{o.label}</span>
                      <span className="text-xs text-muted-foreground">{o.description}</span>
                    </div>
                  </button>
                )
              })}
            </div>
          )}

          {/* Step 2: Add Notes */}
          {step === 'add-notes' && selectedOutcome && (
            <div className="space-y-4">
              {/* Selected outcome badge */}
              <div className="flex items-center gap-2">
                <div className={cn('px-3 py-1.5 rounded-lg flex items-center gap-2 text-xs font-label', selectedOutcome.bg, selectedOutcome.border, 'border')}>
                  <selectedOutcome.icon size={14} className={selectedOutcome.color} />
                  <span className={selectedOutcome.color}>{selectedOutcome.label}</span>
                </div>
                <button
                  onClick={() => setStep('select-outcome')}
                  className="text-xs text-muted-foreground hover:text-foreground transition-colors"
                >
                  Change
                </button>
              </div>

              <div>
                <label className="font-label text-[0.625rem] uppercase tracking-widest text-muted-foreground block mb-2">
                  Additional Notes (optional)
                </label>
                <textarea
                  value={notes}
                  onChange={e => setNotes(e.target.value)}
                  placeholder={
                    outcome === 'resolved'
                      ? 'Any additional context about the resolution...'
                      : outcome === 'escalated'
                      ? 'Reason for escalation, who to assign to...'
                      : 'What still needs to be done, where you left off...'
                  }
                  rows={4}
                  className="w-full resize-none rounded-xl border bg-card text-foreground text-sm placeholder:text-muted-foreground px-4 py-3 focus:outline-hidden focus:border-[rgba(6,182,212,0.3)]"
                  style={{ borderColor: 'var(--glass-border)' }}
                />
              </div>

              {error && (
                <div className="text-sm text-rose-400 bg-rose-400/10 border border-rose-400/20 rounded-lg px-4 py-2">
                  {error}
                </div>
              )}
            </div>
          )}

          {/* Step 3: Summary */}
          {step === 'summary' && (
            <div className="space-y-4">
              {/* Outcome badge */}
              {selectedOutcome && (
                <div className={cn('px-3 py-1.5 rounded-lg inline-flex items-center gap-2 text-xs font-label', selectedOutcome.bg, selectedOutcome.border, 'border')}>
                  <selectedOutcome.icon size={14} className={selectedOutcome.color} />
                  <span className={selectedOutcome.color}>{selectedOutcome.label}</span>
                </div>
              )}

              {/* Generated summary */}
              <div
                className="rounded-xl border p-5 bg-[rgba(255,255,255,0.02)]"
                style={{ borderColor: 'var(--glass-border)' }}
              >
                <div className="flex items-center justify-between mb-3">
                  <span className="font-label text-[0.625rem] uppercase tracking-widest text-muted-foreground flex items-center gap-1.5">
                    <Sparkles size={10} className="text-primary" />
                    Generated Ticket Notes
                  </span>
                </div>
                <div className="prose-sm text-foreground">
                  <MarkdownContent content={summary} className="text-[0.8125rem] leading-relaxed" />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Footer actions */}
        <div
          className="px-6 py-4 border-t shrink-0 flex items-center justify-between gap-3"
          style={{ borderColor: 'var(--glass-border)' }}
        >
          {step === 'select-outcome' && (
            <>
              <div />
              <button
                onClick={onClose}
                className="px-4 py-2 rounded-[10px] text-sm text-muted-foreground hover:text-foreground bg-[rgba(255,255,255,0.04)] border border-brand-border hover:border-[rgba(255,255,255,0.12)] transition-all"
              >
                Cancel
              </button>
            </>
          )}

          {step === 'add-notes' && (
            <>
              <button
                onClick={() => setStep('select-outcome')}
                className="px-4 py-2 rounded-[10px] text-sm text-muted-foreground hover:text-foreground bg-[rgba(255,255,255,0.04)] border border-brand-border hover:border-[rgba(255,255,255,0.12)] transition-all"
              >
                Back
              </button>
              <button
                onClick={handleGenerate}
                disabled={generating}
                className="flex items-center gap-2 bg-gradient-brand text-brand-dark font-semibold text-sm rounded-[10px] px-5 py-2.5 hover:opacity-90 active:scale-[0.97] transition-all disabled:opacity-50"
              >
                {generating ? (
                  <>
                    <Loader2 size={15} className="animate-spin" />
                    Generating...
                  </>
                ) : (
                  <>
                    <Sparkles size={15} />
                    Generate Summary
                  </>
                )}
              </button>
            </>
          )}

          {step === 'summary' && (
            <>
              <div className="flex items-center gap-2">
                {outcome === 'paused' && (
                  <button
                    onClick={handleResumeNew}
                    className="flex items-center gap-2 px-4 py-2.5 rounded-[10px] text-sm font-medium text-blue-400 bg-blue-400/10 border border-blue-400/20 hover:bg-blue-400/15 transition-all"
                  >
                    <RefreshCw size={14} />
                    Resume in New Chat
                  </button>
                )}
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={handleCopy}
                  className={cn(
                    'flex items-center gap-2 px-4 py-2.5 rounded-[10px] text-sm font-semibold transition-all',
                    copied
                      ? 'bg-emerald-400/15 text-emerald-400 border border-emerald-400/30'
                      : 'bg-gradient-brand text-brand-dark hover:opacity-90 active:scale-[0.97]'
                  )}
                >
                  {copied ? (
                    <>
                      <Check size={15} />
                      Copied!
                    </>
                  ) : (
                    <>
                      <Copy size={15} />
                      Copy to Clipboard
                    </>
                  )}
                </button>
                <button
                  onClick={onClose}
                  className="px-4 py-2.5 rounded-[10px] text-sm text-muted-foreground hover:text-foreground bg-[rgba(255,255,255,0.04)] border border-brand-border hover:border-[rgba(255,255,255,0.12)] transition-all"
                >
                  Done
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
