'use client'

import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { CheckCircle, XCircle, Eye, Calendar, User as UserIcon } from 'lucide-react'
import { formatDistanceToNow } from 'date-fns'

interface ReviewPrompt {
  id: string
  name: string
  description: string | null
  content: string
  visibility: string | null
  createdAt: string
  updatedAt: string
  user: {
    username: string | null
    email: string
  }
}

export default function AdminReviewPage() {
  const t = useTranslations('admin')
  const [prompts, setPrompts] = useState<ReviewPrompt[]>([])
  const [loading, setLoading] = useState(true)

  const fetchPendingPrompts = async () => {
    try {
      const response = await fetch('/api/admin/prompts/pending')
      if (response.ok) {
        const data = await response.json()
        setPrompts(data.prompts)
      }
    } catch (error) {
      console.error('Failed to fetch pending prompts:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchPendingPrompts()
  }, [])

  const handleApprove = async (promptId: string) => {
    try {
      const response = await fetch(`/api/admin/prompts/${promptId}/approve`, {
        method: 'POST'
      })
      if (response.ok) {
        setPrompts(prompts.filter(p => p.id !== promptId))
      }
    } catch (error) {
      console.error('Failed to approve prompt:', error)
    }
  }

  const handleReject = async (promptId: string) => {
    try {
      const response = await fetch(`/api/admin/prompts/${promptId}/reject`, {
        method: 'POST'
      })
      if (response.ok) {
        setPrompts(prompts.filter(p => p.id !== promptId))
      }
    } catch (error) {
      console.error('Failed to reject prompt:', error)
    }
  }

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="mb-8">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4">
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-2">
                {t('allPrompts')}
              </h1>
              <p className="text-muted-foreground">
                {t('reviewPromptsDesc')}
              </p>
            </div>
          </div>
        </div>
        
        {/* Loading State */}
        <div className="flex items-center justify-center min-h-96">
          <div className="flex flex-col items-center gap-3">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            <p className="text-sm text-muted-foreground">{t('loadingPrompts')}</p>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="mb-8">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-2">
              {t('allPrompts')}
            </h1>
            <p className="text-muted-foreground">
              {t('reviewPromptsDesc')}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Badge variant="secondary" className="text-xs sm:text-sm">
              {prompts.filter(p => !p.visibility || p.visibility === 'under_review').length} {t('pending')}
            </Badge>
            <Badge variant="outline" className="text-xs sm:text-sm">
              {prompts.filter(p => p.visibility === 'published').length} {t('published')}
            </Badge>
          </div>
        </div>
      </div>

      {/* Content */}
      {prompts.length === 0 ? (
        <Card className="p-8 lg:p-12 text-center">
          <div className="max-w-md mx-auto">
            <CheckCircle className="h-12 w-12 lg:h-16 lg:w-16 text-green-500 mx-auto mb-4" />
            <h3 className="text-lg lg:text-xl font-semibold text-foreground mb-2">
              {t('noPromptsPending')}
            </h3>
            <p className="text-muted-foreground">
              {t('allPromptsReviewed')}
            </p>
          </div>
        </Card>
      ) : (
        <div className="space-y-4 lg:space-y-6">
          {prompts.map((prompt) => (
            <Card key={prompt.id} className="p-4 lg:p-6 border-border hover:border-primary/20 transition-all duration-200">
              <div className="space-y-4">
                {/* Header */}
                <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                  <div className="space-y-1 min-w-0 flex-1">
                    <h3 className="text-lg lg:text-xl font-semibold text-foreground break-words">
                      {prompt.name}
                    </h3>
                    {prompt.description && (
                      <p className="text-sm text-muted-foreground line-clamp-2 break-words">
                        {prompt.description}
                      </p>
                    )}
                  </div>
                  <div className="flex-shrink-0">
                    <Badge 
                      variant={prompt.visibility === 'published' ? 'default' : 'outline'}
                      className={`text-xs sm:text-sm ${
                        prompt.visibility === 'published' 
                          ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' 
                          : ''
                      }`}
                    >
                      {prompt.visibility === 'published' ? t('published') : t('underReview')}
                    </Badge>
                  </div>
                </div>

                {/* Metadata */}
                <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4 text-sm text-muted-foreground">
                  <div className="flex items-center gap-1">
                    <UserIcon className="h-4 w-4 flex-shrink-0" />
                    <span className="truncate">{prompt.user.username || prompt.user.email}</span>
                  </div>
                  <div className="flex items-center gap-1">
                    <Calendar className="h-4 w-4 flex-shrink-0" />
                    <span className="whitespace-nowrap">
                      {formatDistanceToNow(new Date(prompt.createdAt), { addSuffix: true })}
                    </span>
                  </div>
                </div>

                {/* Content Preview */}
                <div className="border border-border rounded-lg p-3 lg:p-4 bg-muted/30">
                  <div className="flex items-center gap-2 mb-2">
                    <Eye className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                    <span className="text-sm font-medium text-muted-foreground">
                      {t('promptContent')}
                    </span>
                  </div>
                  <div className="text-sm text-foreground max-h-32 lg:max-h-40 overflow-y-auto break-words">
                    {prompt.content.length > 500 
                      ? `${prompt.content.slice(0, 500)}...` 
                      : prompt.content
                    }
                  </div>
                </div>

                {/* Actions */}
                <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 pt-2 border-t border-border/50">
                  {prompt.visibility !== 'published' && (
                    <Button
                      onClick={() => handleApprove(prompt.id)}
                      className="bg-green-600 hover:bg-green-700 text-white w-full sm:w-auto"
                      size="sm"
                    >
                      <CheckCircle className="h-4 w-4 mr-2" />
                      {t('approve')}
                    </Button>
                  )}
                  <Button
                    onClick={() => handleReject(prompt.id)}
                    variant="destructive"
                    size="sm"
                    className="w-full sm:w-auto"
                  >
                    <XCircle className="h-4 w-4 mr-2" />
                    {t('reject')}
                  </Button>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}