import { useState, useEffect } from 'react'
import { X, Star, Copy, Check, HelpCircle, Zap, CheckCircle, User, Calendar, GitBranch } from 'lucide-react'
import { cn } from '@/lib/utils'
import { MarkdownContent } from '@/components/ui/MarkdownContent'
import { stepsApi } from '@/api/steps'
import type { Step, Review } from '@/types/step'

interface StepDetailModalProps {
  stepId: string
  onClose: () => void
  onInsert: (step: Step) => void
}

const stepTypeIcons = {
  decision: HelpCircle,
  action: Zap,
  solution: CheckCircle
}

const stepTypeColors = {
  decision: 'bg-blue-400/10 text-blue-400 border-blue-400/20',
  action: 'bg-yellow-400/10 text-yellow-400 border-yellow-400/20',
  solution: 'bg-emerald-400/10 text-emerald-400 border-emerald-400/20'
}

export function StepDetailModal({ stepId, onClose, onInsert }: StepDetailModalProps) {
  const [step, setStep] = useState<Step | null>(null)
  const [reviews, setReviews] = useState<Review[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [copiedCommandIndex, setCopiedCommandIndex] = useState<number | null>(null)

  useEffect(() => {
    const loadStepDetails = async () => {
      setIsLoading(true)
      setError(null)
      try {
        const [stepData, reviewsData] = await Promise.all([
          stepsApi.get(stepId),
          stepsApi.getReviews(stepId)
        ])
        setStep(stepData)
        setReviews(reviewsData)
      } catch (err) {
        console.error('Failed to load step details:', err)
        setError('Failed to load step details')
      } finally {
        setIsLoading(false)
      }
    }

    loadStepDetails()
  }, [stepId])

  const handleCopyCommand = async (command: string, index: number) => {
    await navigator.clipboard.writeText(command)
    setCopiedCommandIndex(index)
    setTimeout(() => setCopiedCommandIndex(null), 2000)
  }

  const handleInsert = () => {
    if (step) {
      onInsert(step)
    }
  }

  const Icon = step ? stepTypeIcons[step.step_type as keyof typeof stepTypeIcons] : HelpCircle
  const hasRating = step && step.rating_count > 0
  const topReviews = reviews.filter(r => r.review_text).slice(0, 3)

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm">
      <div className="relative flex h-[90vh] w-full max-w-3xl flex-col bg-card border border-border rounded-2xl shadow-lg">
        {/* Header */}
        <div className="flex items-start justify-between border-b border-border p-6 pb-4">
          {isLoading ? (
            <div className="h-6 w-48 animate-pulse rounded bg-accent" />
          ) : error ? (
            <h2 className="text-lg font-semibold text-red-400">{error}</h2>
          ) : step ? (
            <div className="flex-1">
              <div className="mb-2 flex items-center gap-2">
                <span
                  className={cn(
                    'flex items-center gap-1 rounded border px-2 py-0.5 text-xs font-medium',
                    stepTypeColors[step.step_type as keyof typeof stepTypeColors]
                  )}
                >
                  <Icon className="h-3 w-3" />
                  {step.step_type}
                </span>
                {step.category_name && (
                  <span className="text-xs text-muted-foreground">{step.category_name}</span>
                )}
                {step.is_featured && (
                  <span className="rounded bg-yellow-400/10 px-2 py-0.5 text-xs font-medium text-yellow-400">
                    Featured
                  </span>
                )}
                {step.is_verified && (
                  <span className="rounded bg-emerald-400/10 px-2 py-0.5 text-xs font-medium text-emerald-400">
                    Verified
                  </span>
                )}
              </div>
              <h2 className="text-xl font-semibold text-foreground">{step.title}</h2>
            </div>
          ) : null}
          <button
            onClick={onClose}
            className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
            aria-label="Close"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Body - Scrollable */}
        <div className="flex-1 overflow-y-auto p-6">
          {isLoading ? (
            <div className="space-y-4">
              <div className="h-4 w-full animate-pulse rounded bg-accent" />
              <div className="h-4 w-3/4 animate-pulse rounded bg-accent" />
              <div className="h-4 w-5/6 animate-pulse rounded bg-accent" />
            </div>
          ) : error ? (
            <p className="text-sm text-muted-foreground">{error}</p>
          ) : step ? (
            <div className="space-y-6">
              {/* Rating */}
              {hasRating && (
                <div>
                  <h3 className="mb-2 text-sm font-semibold text-foreground">Rating</h3>
                  <div className="flex items-center gap-2">
                    <div className="flex items-center gap-1">
                      {[1, 2, 3, 4, 5].map(i => (
                        <Star
                          key={i}
                          className={cn(
                            'h-4 w-4',
                            i <= Math.round(step.rating_average)
                              ? 'fill-yellow-400 text-yellow-400'
                              : 'text-muted-foreground'
                          )}
                        />
                      ))}
                    </div>
                    <span className="text-sm text-muted-foreground">
                      {step.rating_average.toFixed(1)} ({step.rating_count} {step.rating_count === 1 ? 'rating' : 'ratings'})
                    </span>
                  </div>
                </div>
              )}

              {/* Tags */}
              {step.tags.length > 0 && (
                <div>
                  <h3 className="mb-2 text-sm font-semibold text-foreground">Tags</h3>
                  <div className="flex flex-wrap gap-1.5">
                    {step.tags.map(tag => (
                      <span
                        key={tag}
                        className="rounded-full bg-accent px-2 py-1 text-xs text-muted-foreground"
                      >
                        {tag}
                      </span>
                    ))}
                  </div>
                </div>
              )}

              {/* Instructions */}
              <div>
                <h3 className="mb-2 text-sm font-semibold">Instructions</h3>
                <div className="rounded-lg border border-border bg-accent/50 p-4">
                  <MarkdownContent content={step.content.instructions} />
                </div>
              </div>

              {/* Help Text */}
              {step.content.help_text && (
                <div>
                  <h3 className="mb-2 text-sm font-semibold text-foreground">Help Text</h3>
                  <div className="rounded-lg border border-border bg-blue-400/5 p-4 text-sm">
                    <MarkdownContent content={step.content.help_text} />
                  </div>
                </div>
              )}

              {/* Commands */}
              {step.content.commands && step.content.commands.length > 0 && (
                <div>
                  <h3 className="mb-2 text-sm font-semibold text-foreground">Commands</h3>
                  <div className="space-y-2">
                    {step.content.commands.map((cmd, index) => (
                      <div key={index} className="group relative">
                        <div className="mb-1 flex items-center justify-between">
                          <span className="text-xs font-medium text-muted-foreground">{cmd.label}</span>
                          <button
                            onClick={() => handleCopyCommand(cmd.command, index)}
                            className={cn(
                              'flex items-center gap-1 rounded px-2 py-1 text-xs transition-colors',
                              copiedCommandIndex === index
                                ? 'bg-emerald-400/10 text-emerald-400'
                                : 'bg-accent text-muted-foreground hover:bg-accent hover:text-foreground'
                            )}
                          >
                            {copiedCommandIndex === index ? (
                              <>
                                <Check className="h-3 w-3" />
                                Copied
                              </>
                            ) : (
                              <>
                                <Copy className="h-3 w-3" />
                                Copy
                              </>
                            )}
                          </button>
                        </div>
                        <pre className="overflow-x-auto rounded bg-card p-3 text-xs text-foreground">
                          <code>{cmd.command}</code>
                        </pre>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Reviews */}
              {topReviews.length > 0 && (
                <div>
                  <div className="mb-2 flex items-center justify-between">
                    <h3 className="text-sm font-semibold text-foreground">Reviews</h3>
                    {reviews.length > 3 && (
                      <button className="text-xs text-muted-foreground hover:text-foreground hover:underline">
                        See all {reviews.length} reviews
                      </button>
                    )}
                  </div>
                  <div className="space-y-3">
                    {topReviews.map(review => (
                      <div key={review.id} className="rounded-lg border border-border bg-accent/50 p-3">
                        <div className="mb-2 flex items-center justify-between">
                          <div className="flex items-center gap-2 text-sm">
                            <User className="h-3.5 w-3.5" />
                            <span className="font-medium text-foreground">{review.user_name || 'Anonymous'}</span>
                            {review.verified_use && (
                              <span className="rounded bg-emerald-400/10 px-1.5 py-0.5 text-xs text-emerald-400">
                                Verified Use
                              </span>
                            )}
                          </div>
                          <div className="flex items-center gap-1">
                            {[1, 2, 3, 4, 5].map(i => (
                              <Star
                                key={i}
                                className={cn(
                                  'h-3 w-3',
                                  i <= review.rating
                                    ? 'fill-yellow-400 text-yellow-400'
                                    : 'text-muted-foreground'
                                )}
                              />
                            ))}
                          </div>
                        </div>
                        <p className="text-sm text-muted-foreground">{review.review_text}</p>
                        <div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
                          <Calendar className="h-3 w-3" />
                          {new Date(review.created_at).toLocaleDateString()}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Metadata */}
              <div className="rounded-lg border border-border bg-accent/50 p-4">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">Author:</span>
                    <span className="ml-2 font-medium text-foreground">{step.author_name || 'Unknown'}</span>
                  </div>
                  {step.is_flow_synced && step.source_tree_name && (
                    <div className="col-span-2 flex items-center gap-1.5 text-muted-foreground">
                      <GitBranch className="h-3.5 w-3.5 shrink-0" />
                      <span>Sourced from <span className="font-medium text-foreground">{step.source_tree_name}</span></span>
                    </div>
                  )}
                  <div>
                    <span className="text-muted-foreground">Usage Count:</span>
                    <span className="ml-2 font-medium text-foreground">{step.usage_count}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Created:</span>
                    <span className="ml-2 font-medium text-foreground">{new Date(step.created_at).toLocaleDateString()}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">Visibility:</span>
                    <span className="ml-2 font-medium capitalize">{step.visibility}</span>
                  </div>
                </div>
              </div>
            </div>
          ) : null}
        </div>

        {/* Footer - Actions */}
        <div className="flex gap-2 border-t border-border p-4">
          <button
            onClick={onClose}
            className="flex-1 rounded-md border border-border px-4 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
          >
            Cancel
          </button>
          <button
            onClick={handleInsert}
            disabled={!step}
            className={cn(
              'flex-1 rounded-md bg-gradient-brand px-4 py-2 text-sm font-medium text-white shadow-lg shadow-primary/20',
              'hover:opacity-90 disabled:opacity-50'
            )}
          >
            Insert Into Session
          </button>
        </div>
      </div>
    </div>
  )
}
