import { useState, useEffect, useRef } from 'react'
import {
  X,
  CheckCircle2,
  ArrowUpRight,
  Pause,
  Loader2,
  Copy,
  Check,
  RefreshCw,
  ClipboardList,
  Sparkles,
  AlertTriangle,
  FileText,
  User,
  Mail,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { MarkdownContent } from '@/components/ui/MarkdownContent'
import { aiSessionsApi } from '@/api/aiSessions'

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

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

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-success',
    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-warning',
    bg: 'bg-warning-dim',
    border: 'border-warning/30',
  },
  {
    value: 'paused',
    label: 'Paused',
    description: 'Continuing later — saving progress',
    icon: Pause,
    color: 'text-accent',
    bg: 'bg-accent-dim',
    border: 'border-blue-400/30',
  },
]

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

export function ConcludeSessionModal({
  isOpen,
  onClose,
  onConclude,
  onResumeNew,
  chatTitle,
  sessionId,
}: 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)
  const [streaming, setStreaming] = useState(false)
  const [streamError, setStreamError] = useState<string | null>(null)
  const [generatingUpdate, setGeneratingUpdate] = useState(false)
  const summaryRef = useRef('')

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

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

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

    try {
      // Phase 1: Resolve/escalate/pause the session (fast)
      await onConclude(outcome, notes)

      // Phase 2: Transition to summary step immediately
      setStep('summary')
      setGenerating(false)

      // For resolved sessions, stream ticket notes
      if (outcome === 'resolved' && sessionId) {
        setStreaming(true)
        setStreamError(null)
        summaryRef.current = ''

        aiSessionsApi.streamDocumentation(
          sessionId,
          (chunk) => {
            summaryRef.current += chunk
            setSummary(summaryRef.current)
          },
          () => {
            setStreaming(false)
          },
          (err) => {
            setStreaming(false)
            setStreamError(err)
            // Fallback: use status update API which works with conversation context
            aiSessionsApi.generateStatusUpdate(sessionId, {
              audience: 'ticket_notes',
              length: 'detailed',
              context: 'resolution',
            }).then((result) => {
              setSummary(result.content)
              setStreamError(null)
            }).catch(() => {
              if (!summaryRef.current) {
                setSummary('Documentation generation failed. You can copy the conversation from the chat.')
              }
            })
          },
        )
      } else {
        // For paused/escalated: don't set summary yet — show status update options
        setSummary('')
      }
    } catch {
      setError('Failed to conclude session. Please try again.')
      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()
  }

  const handleGenerateStatusUpdate = async (audience: 'ticket_notes' | 'client_update' | 'email_draft') => {
    if (!sessionId) return
    setGeneratingUpdate(true)
    try {
      const context = outcome === 'escalated' ? 'escalation' : 'status'
      const result = await aiSessionsApi.generateStatusUpdate(sessionId, {
        audience,
        length: 'detailed',
        context,
      })
      setSummary(result.content)
      setCopied(false)
    } catch {
      setSummary('Failed to generate status update. You can copy the conversation from the chat.')
    } finally {
      setGeneratingUpdate(false)
    }
  }

  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"
        onClick={onClose}
      />

      {/* Modal */}
      <div
        className="relative w-full max-w-2xl mx-4 card-flat 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(--color-border-default)' }}
        >
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-xl bg-accent-dim 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-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(--color-border-default)' }}
        >
          {(['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-sans text-xs font-medium transition-colors',
                  step === s
                    ? 'bg-primary text-white'
                    : (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-sans text-xs',
                  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-card border-border',
                      'hover:border-border-hover hover:bg-input'
                    )}
                  >
                    <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-sans text-xs', 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-sans text-xs 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-primary/30"
                  style={{ borderColor: 'var(--color-border-default)' }}
                />
              </div>

              {error && (
                <div className="text-sm text-danger bg-danger-dim border border-danger/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-sans text-xs', selectedOutcome.bg, selectedOutcome.border, 'border')}>
                  <selectedOutcome.icon size={14} className={selectedOutcome.color} />
                  <span className={selectedOutcome.color}>{selectedOutcome.label}</span>
                </div>
              )}

              {/* Resolved: streamed ticket notes */}
              {outcome === 'resolved' && (
                <div
                  className="rounded-xl border p-5 bg-card"
                  style={{ borderColor: 'var(--color-border-default)' }}
                >
                  <div className="flex items-center justify-between mb-3">
                    <span className="font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground flex items-center gap-1.5">
                      <Sparkles size={10} className="text-primary" />
                      Ticket Notes
                    </span>
                    {streaming && (
                      <Loader2 size={14} className="animate-spin text-primary" />
                    )}
                  </div>

                  {summary ? (
                    <div className="prose-sm text-foreground">
                      <MarkdownContent content={summary} className="text-[0.8125rem] leading-relaxed" />
                    </div>
                  ) : streaming ? (
                    <div className="space-y-3 animate-pulse">
                      <div className="h-4 bg-elevated rounded w-1/3" />
                      <div className="h-3 bg-elevated rounded w-full" />
                      <div className="h-3 bg-elevated rounded w-5/6" />
                      <div className="h-4 bg-elevated rounded w-1/4 mt-4" />
                      <div className="h-3 bg-elevated rounded w-full" />
                      <div className="h-3 bg-elevated rounded w-4/5" />
                    </div>
                  ) : streamError ? (
                    <div className="flex items-center gap-2 text-sm text-warning">
                      <AlertTriangle size={14} />
                      {streamError}
                    </div>
                  ) : null}
                </div>
              )}

              {/* Paused/Escalated: status update options */}
              {(outcome === 'paused' || outcome === 'escalated') && !summary && !generatingUpdate && (
                <div className="space-y-3">
                  <p className="text-sm text-muted-foreground">
                    {outcome === 'paused'
                      ? 'Session paused. Generate a status update to share progress.'
                      : 'Session escalated. Generate an update to document the handoff.'}
                  </p>
                  <div className="space-y-2">
                    <button
                      onClick={() => handleGenerateStatusUpdate('ticket_notes')}
                      className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-left transition-colors hover:bg-[var(--color-bg-elevated)]"
                      style={{ border: '1px solid var(--color-border-default)' }}
                    >
                      <FileText size={18} className="text-muted-foreground shrink-0" />
                      <div>
                        <p className="text-sm font-medium text-foreground">Ticket Notes</p>
                        <p className="text-xs text-muted-foreground">Technical, for your PSA</p>
                      </div>
                    </button>
                    <button
                      onClick={() => handleGenerateStatusUpdate('client_update')}
                      className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-left transition-colors hover:bg-[var(--color-bg-elevated)]"
                      style={{ border: '1px solid var(--color-border-default)' }}
                    >
                      <User size={18} className="text-muted-foreground shrink-0" />
                      <div>
                        <p className="text-sm font-medium text-foreground">Client Update</p>
                        <p className="text-xs text-muted-foreground">Professional, non-technical</p>
                      </div>
                    </button>
                    <button
                      onClick={() => handleGenerateStatusUpdate('email_draft')}
                      className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-left transition-colors hover:bg-[var(--color-bg-elevated)]"
                      style={{ border: '1px solid var(--color-border-default)' }}
                    >
                      <Mail size={18} className="text-muted-foreground shrink-0" />
                      <div>
                        <p className="text-sm font-medium text-foreground">Email Draft</p>
                        <p className="text-xs text-muted-foreground">Full email with subject line</p>
                      </div>
                    </button>
                  </div>
                </div>
              )}

              {/* Paused/Escalated: generating spinner */}
              {(outcome === 'paused' || outcome === 'escalated') && generatingUpdate && (
                <div className="flex flex-col items-center justify-center py-8 gap-3">
                  <Loader2 size={24} className="animate-spin text-accent" />
                  <p className="text-sm text-muted-foreground">Generating status update...</p>
                </div>
              )}

              {/* Paused/Escalated: generated result */}
              {(outcome === 'paused' || outcome === 'escalated') && summary && !generatingUpdate && (
                <div
                  className="rounded-xl border p-5 bg-card"
                  style={{ borderColor: 'var(--color-border-default)' }}
                >
                  <div className="flex items-center justify-between mb-3">
                    <span className="font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground flex items-center gap-1.5">
                      <Sparkles size={10} className="text-primary" />
                      Status Update
                    </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(--color-border-default)' }}
        >
          {step === 'select-outcome' && (
            <>
              <div />
              <button
                onClick={onClose}
                className="px-4 py-2 rounded-lg text-sm text-muted-foreground hover:text-foreground bg-input border border-border hover:border-border-hover transition-all"
              >
                Cancel
              </button>
            </>
          )}

          {step === 'add-notes' && (
            <>
              <button
                onClick={() => setStep('select-outcome')}
                className="px-4 py-2 rounded-lg text-sm text-muted-foreground hover:text-foreground bg-input border border-border hover:border-border-hover transition-all"
              >
                Back
              </button>
              <button
                onClick={handleGenerate}
                disabled={generating}
                className="flex items-center gap-2 bg-primary text-white font-semibold text-sm rounded-lg px-5 py-2.5 hover:brightness-110 active:scale-[0.98] 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-lg text-sm font-medium text-accent bg-accent-dim border border-accent/20 hover:bg-accent/15 transition-all"
                  >
                    <RefreshCw size={14} />
                    Resume in New Chat
                  </button>
                )}
                {(outcome === 'paused' || outcome === 'escalated') && summary && !generatingUpdate && (
                  <button
                    onClick={() => { setSummary(''); setCopied(false) }}
                    className="flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground bg-input border border-border hover:border-border-hover transition-all"
                  >
                    Switch Format
                  </button>
                )}
              </div>
              <div className="flex items-center gap-2">
                {summary && !streaming && !generatingUpdate && (
                  <button
                    onClick={handleCopy}
                    className={cn(
                      'flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-semibold transition-all',
                      copied
                        ? 'bg-emerald-400/15 text-success border border-emerald-400/30'
                        : 'bg-primary text-white hover:brightness-110 active:scale-[0.98]'
                    )}
                  >
                    {copied ? (
                      <>
                        <Check size={15} />
                        Copied!
                      </>
                    ) : (
                      <>
                        <Copy size={15} />
                        Copy to Clipboard
                      </>
                    )}
                  </button>
                )}
                <button
                  onClick={onClose}
                  className="px-4 py-2.5 rounded-lg text-sm text-muted-foreground hover:text-foreground bg-input border border-border hover:border-border-hover transition-all"
                >
                  Done
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  )
}
