import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { toast } from '@/lib/toast'
import {
  CheckCircle2, XCircle, Pencil, EyeOff, ChevronDown, ChevronRight,
  ExternalLink, Clock, Hash, Sparkles, Loader2,
} from 'lucide-react'
import type { FlowProposalDetail as ProposalDetailType } from '@/types/flow-proposal'

interface ProposalDetailProps {
  proposal: ProposalDetailType
  onReview: (action: 'approve' | 'reject' | 'modify' | 'dismiss', notes?: string) => Promise<void>
}

export function ProposalDetail({ proposal, onReview }: ProposalDetailProps) {
  const navigate = useNavigate()
  const [reviewNotes, setReviewNotes] = useState('')
  const [showFlowData, setShowFlowData] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showRejectConfirm, setShowRejectConfirm] = useState(false)

  const canReview = proposal.status === 'pending' || proposal.status === 'dismissed'

  const handleAction = async (action: 'approve' | 'reject' | 'modify' | 'dismiss') => {
    setIsSubmitting(true)
    try {
      await onReview(action, reviewNotes || undefined)
    } finally {
      setIsSubmitting(false)
      setShowRejectConfirm(false)
    }
  }

  const handleEditAndPublish = async () => {
    // Mark proposal as dismissed so it doesn't stay in the pending queue.
    // The tree editor will create the flow independently.
    // TODO: Wire tree editor to call review API with action='modify' on save
    // when it detects proposalId in location.state, linking the published tree
    // back to the proposal.
    setIsSubmitting(true)
    try {
      await onReview('dismiss', 'Opened in Flow Editor for manual editing')
    } catch {
      // Warn but continue — the editor will still open
      toast.warning('Could not update proposal status — it may still appear in the queue')
    } finally {
      setIsSubmitting(false)
    }

    const flowData = proposal.proposed_flow_data
    navigate('/trees/new', {
      state: {
        preloadedStructure: flowData.tree_structure || flowData,
        proposalId: proposal.id,
        proposalTitle: proposal.title,
      },
    })
  }

  return (
    <div className="flex h-full flex-col">
      {/* Header */}
      <div className="border-b px-6 py-4" style={{ borderColor: 'var(--color-border-default)' }}>
        <h2 className="font-heading text-lg font-semibold text-foreground">{proposal.title}</h2>
        {proposal.description && (
          <p className="mt-1 text-sm text-muted-foreground">{proposal.description}</p>
        )}
        <div className="mt-3 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
          {proposal.problem_domain && (
            <span className="font-sans text-xs rounded-md bg-accent-dim px-2 py-0.5 text-[0.625rem] uppercase tracking-wider text-primary">
              {proposal.problem_domain}
            </span>
          )}
          <span className="flex items-center gap-1">
            <Sparkles size={12} />
            {Math.round(proposal.confidence_score * 100)}% confidence
          </span>
          <span className="flex items-center gap-1">
            <Hash size={12} />
            {proposal.supporting_session_count} supporting session{proposal.supporting_session_count !== 1 ? 's' : ''}
          </span>
          <span className="flex items-center gap-1">
            <Clock size={12} />
            {new Date(proposal.created_at).toLocaleString()}
          </span>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-6 space-y-5">
        {/* Source session link */}
        <div className="card-flat p-4">
          <h4 className="font-sans text-xs text-[0.625rem] uppercase tracking-wider text-text-muted mb-2">Source Session</h4>
          <Link
            to={`/pilot/${proposal.source_session_id}`}
            target="_blank"
            className="flex items-center gap-2 text-sm text-primary hover:underline"
          >
            <ExternalLink size={12} />
            View session that generated this proposal
          </Link>
        </div>

        {/* Proposed diff (for enhancements) */}
        {proposal.proposed_diff && (() => {
          const diff = proposal.proposed_diff as { diff_description?: string; new_nodes?: Array<{ title?: string; question?: string; description?: string }> }
          return (
            <div className="card-flat border-l-2 border-l-warning p-4">
              <h4 className="font-sans text-xs text-[0.625rem] uppercase tracking-wider text-text-muted mb-2">Proposed Changes</h4>
              {diff.diff_description && (
                <p className="text-sm text-foreground">{diff.diff_description}</p>
              )}
              {diff.new_nodes && diff.new_nodes.length > 0 && (
                <div className="mt-3 space-y-1.5">
                  <p className="text-xs font-medium text-muted-foreground">New nodes:</p>
                  {diff.new_nodes.map((node, i) => (
                    <div key={i} className="rounded-lg bg-success/5 border border-success/10 px-3 py-2 text-xs text-foreground">
                      <span className="text-success">+ </span>
                      {node.title || node.question || node.description || 'New node'}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )
        })()}

        {/* Flow data preview */}
        <div className="card-flat p-4">
          <button
            onClick={() => setShowFlowData(!showFlowData)}
            className="flex items-center gap-1.5 font-sans text-xs text-[0.625rem] uppercase tracking-wider text-text-muted hover:text-foreground transition-colors"
          >
            {showFlowData ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
            Flow Data (JSON)
          </button>
          {showFlowData && (
            <pre className="mt-3 max-h-[400px] overflow-auto rounded-lg bg-card/80 p-3 text-xs text-muted-foreground font-mono">
              {JSON.stringify(proposal.proposed_flow_data, null, 2)}
            </pre>
          )}
        </div>

        {/* Supporting sessions */}
        {proposal.supporting_session_ids.length > 1 && (
          <div className="card-flat p-4">
            <h4 className="font-sans text-xs text-[0.625rem] uppercase tracking-wider text-text-muted mb-2">
              Supporting Sessions ({proposal.supporting_session_ids.length})
            </h4>
            <div className="space-y-1">
              {proposal.supporting_session_ids.map((sid) => (
                <Link
                  key={sid}
                  to={`/pilot/${sid}`}
                  target="_blank"
                  className="block text-xs text-primary hover:underline truncate"
                >
                  {sid}
                </Link>
              ))}
            </div>
          </div>
        )}

        {/* Review info (for already-reviewed proposals) */}
        {proposal.reviewed_at && (
          <div className="card-flat p-4">
            <h4 className="font-sans text-xs text-[0.625rem] uppercase tracking-wider text-text-muted mb-2">Review</h4>
            <p className="text-sm text-foreground">
              <span className="capitalize">{proposal.status}</span> on{' '}
              {new Date(proposal.reviewed_at).toLocaleString()}
            </p>
            {proposal.reviewer_notes && (
              <p className="mt-1 text-xs text-muted-foreground">{proposal.reviewer_notes}</p>
            )}
          </div>
        )}
      </div>

      {/* Review actions bar */}
      {canReview && (
        <div
          className="border-t border-border bg-card px-5 py-3 space-y-3"
        >
          {/* Notes input */}
          <input
            value={reviewNotes}
            onChange={(e) => setReviewNotes(e.target.value)}
            placeholder="Reviewer notes (optional)"
            className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-[rgba(96,165,250,0.3)] focus:outline-none"
          />

          {/* Action buttons */}
          <div className="flex items-center gap-2">
            {proposal.proposal_type === 'new_flow' ? (
              <button
                onClick={() => handleAction('approve')}
                disabled={isSubmitting}
                className="flex items-center gap-2 rounded-lg bg-success-dim border border-success/20 px-4 py-2 text-sm font-medium text-success hover:bg-success/20 disabled:opacity-40 transition-colors"
              >
                {isSubmitting ? <Loader2 size={14} className="animate-spin" /> : <CheckCircle2 size={14} />}
                Approve & Publish
              </button>
            ) : (
              <span className="text-xs text-muted-foreground italic px-2">
                Enhancement proposals require Edit & Publish
              </span>
            )}
            <button
              onClick={handleEditAndPublish}
              disabled={isSubmitting}
              className="flex items-center gap-2 rounded-lg bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] px-4 py-2 text-sm font-medium text-foreground hover:border-[rgba(255,255,255,0.12)] disabled:opacity-40 transition-colors"
            >
              <Pencil size={14} />
              Edit & Publish
            </button>
            <button
              onClick={() => handleAction('dismiss')}
              disabled={isSubmitting}
              className="flex items-center gap-2 rounded-lg bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-[rgba(255,255,255,0.12)] disabled:opacity-40 transition-colors ml-auto"
            >
              <EyeOff size={14} />
              Dismiss
            </button>
            <button
              onClick={() => showRejectConfirm ? handleAction('reject') : setShowRejectConfirm(true)}
              disabled={isSubmitting}
              className="flex items-center gap-2 rounded-lg bg-danger-dim border border-danger/20 px-4 py-2 text-sm font-medium text-danger hover:bg-danger/20 disabled:opacity-40 transition-colors"
            >
              <XCircle size={14} />
              {showRejectConfirm ? 'Confirm Reject' : 'Reject'}
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
