import { useState, useEffect } from 'react'
import { cn } from '@/lib/utils'
import { useWritingCheck } from '@/hooks/use-writing-check'
import { getRemainingChecks } from '@/utils/rate-limiter'
import { useRequireAuth } from '@/hooks/use-require-auth'
import { useAuthStore } from '@/store/auth-store'
import { countTodayWritingSubmissions } from '@/lib/progress-service'

const MAX_CHARS = 1000
const GUEST_LIMIT = 3
const AUTH_LIMIT = 10

export function WritingChecker() {
  const [text, setText] = useState('')
  const [improvedExpanded, setImprovedExpanded] = useState(false)
  const [remaining, setRemaining] = useState(getRemainingChecks)

  const { mutate: checkWriting, isPending, isError, error, data: feedback } = useWritingCheck()
  const { requireAuth } = useRequireAuth()
  const user = useAuthStore((s) => s.user)

  const dailyLimit = user ? AUTH_LIMIT : GUEST_LIMIT

  // Fetch server-side remaining count for authenticated users
  useEffect(() => {
    if (!user) {
      setRemaining(getRemainingChecks())
      return
    }
    countTodayWritingSubmissions(user.id).then((used) => {
      setRemaining(AUTH_LIMIT - used)
    })
  }, [user])

  const charCount = text.length
  const canSubmit = text.trim().length > 0 && remaining > 0 && charCount <= MAX_CHARS && !isPending

  function handleSubmit() {
    if (!requireAuth()) return
    if (!canSubmit) return
    checkWriting(text, {
      onSuccess: () => {
        if (user) {
          countTodayWritingSubmissions(user.id).then((used) => setRemaining(AUTH_LIMIT - used))
        } else {
          setRemaining(getRemainingChecks())
        }
      },
      onError: () => {
        if (!user) setRemaining(getRemainingChecks())
      },
    })
  }

  return (
    <div className="px-4 lg:px-6 py-6 max-w-6xl mx-auto page-enter">
      <div className="mb-6">
        <h1 className="text-2xl font-extrabold text-slate-800 mb-1">AI Chấm Writing</h1>
        <p className="text-slate-500 text-sm">Nhận phản hồi tức thì về ngữ pháp, từ vựng và cấu trúc bài viết.</p>
      </div>

      <div className="flex flex-col lg:flex-row gap-5">
        {/* Left: Input */}
        <div className="flex-1 min-w-0">
          <div className="bg-white rounded-2xl border border-slate-200 p-5">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm font-semibold text-slate-700">Bài writing của bạn</span>
              <span className={cn('text-xs tabular-nums', charCount > MAX_CHARS ? 'text-red-500 font-bold' : 'text-slate-400')}>
                {charCount}/{MAX_CHARS}
              </span>
            </div>
            <textarea
              value={text}
              onChange={(e) => setText(e.target.value.slice(0, MAX_CHARS))}
              rows={12}
              placeholder="Nhập bài writing của bạn vào đây... (TOEIC email, IELTS task, hoặc đoạn văn tự do)"
              className="w-full resize-none rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-blue-400 focus:bg-white transition-colors"
            />
            <div className="mt-3 flex items-center justify-between">
              <div className="flex items-center gap-1.5">
                <span className="material-symbols-outlined text-slate-400" style={{ fontSize: 14 }}>info</span>
                <span className={cn('text-xs font-medium', remaining <= 1 ? 'text-red-500' : 'text-slate-400')}>
                  Còn {remaining}/{dailyLimit} lượt hôm nay
                </span>
              </div>
              <button
                onClick={handleSubmit}
                disabled={!canSubmit}
                className={cn(
                  'flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all',
                  canSubmit
                    ? 'bg-blue-600 text-white hover:bg-blue-700 shadow-lg shadow-blue-600/20'
                    : 'bg-slate-100 text-slate-400 cursor-not-allowed',
                )}
              >
                {isPending ? (
                  <>
                    <span className="w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin" />
                    Đang chấm...
                  </>
                ) : (
                  <>
                    <span className="material-symbols-outlined" style={{ fontSize: 18 }}>auto_fix_high</span>
                    Chấm bài ngay
                  </>
                )}
              </button>
            </div>
          </div>

          {remaining <= 0 && (
            <div className="mt-3 bg-amber-50 border border-amber-100 rounded-xl p-4 flex items-center gap-3">
              <span className="material-symbols-outlined text-amber-600 flex-shrink-0" style={{ fontSize: 20 }}>schedule</span>
              <p className="text-sm text-amber-700">
                Bạn đã dùng hết {dailyLimit} lượt hôm nay. Vui lòng quay lại vào ngày mai.
              </p>
            </div>
          )}

          {isError && (
            <div className="mt-3 bg-red-50 border border-red-100 rounded-xl p-4 flex items-center gap-3">
              <span className="material-symbols-outlined text-red-500 flex-shrink-0" style={{ fontSize: 20 }}>error</span>
              <p className="text-sm text-red-600">
                {(error as Error)?.message ?? 'Đã có lỗi xảy ra. Vui lòng thử lại.'}
              </p>
            </div>
          )}
        </div>

        {/* Right: Feedback */}
        <div className="lg:w-80 flex-shrink-0">
          {!feedback && !isPending && (
            <div className="bg-white rounded-2xl border border-slate-200 p-6 flex flex-col items-center justify-center text-center h-full min-h-48">
              <span className="material-symbols-outlined text-slate-300 mb-3" style={{ fontSize: 48 }}>auto_fix_high</span>
              <p className="text-sm text-slate-400">Nhập bài và nhấn "Chấm bài ngay" để nhận phản hồi từ AI</p>
            </div>
          )}

          {isPending && (
            <div className="bg-white rounded-2xl border border-slate-200 p-6 flex flex-col items-center justify-center text-center h-full min-h-48">
              <div className="w-10 h-10 border-2 border-blue-100 border-t-blue-600 rounded-full animate-spin mb-4" />
              <p className="text-sm text-slate-500 font-medium">AI đang phân tích bài viết...</p>
              <p className="text-xs text-slate-400 mt-1">Thường mất 3–5 giây</p>
            </div>
          )}

          {feedback && !isPending && (
            <div className="space-y-3">
              {/* Band score */}
              <div className="bg-blue-600 rounded-2xl p-5 text-center">
                <div className="text-xs text-blue-200 font-medium mb-1 uppercase tracking-wider">Band Score ước tính</div>
                <div className="text-5xl font-extrabold text-white mb-1">{feedback.score}</div>
                <div className="text-xs text-blue-200">Dựa trên tiêu chí IELTS/TOEIC Writing</div>
              </div>

              {/* Grammar */}
              <div className="bg-white rounded-2xl border border-slate-200 p-4">
                <div className="flex items-center gap-2 mb-3">
                  <div className="w-2 h-2 rounded-full bg-red-500" />
                  <span className="text-sm font-bold text-slate-800">Ngữ pháp</span>
                </div>
                <ul className="space-y-1.5">
                  {feedback.grammar.map((item, i) => (
                    <li key={i} className="text-xs text-slate-600 flex items-start gap-2">
                      <span className="material-symbols-outlined text-red-400 flex-shrink-0 mt-0.5" style={{ fontSize: 14 }}>error</span>
                      {item}
                    </li>
                  ))}
                </ul>
              </div>

              {/* Vocabulary */}
              <div className="bg-white rounded-2xl border border-slate-200 p-4">
                <div className="flex items-center gap-2 mb-3">
                  <div className="w-2 h-2 rounded-full bg-amber-500" />
                  <span className="text-sm font-bold text-slate-800">Từ vựng</span>
                </div>
                <ul className="space-y-1.5">
                  {feedback.vocabulary.map((item, i) => (
                    <li key={i} className="text-xs text-slate-600 flex items-start gap-2">
                      <span className="material-symbols-outlined text-amber-400 flex-shrink-0 mt-0.5" style={{ fontSize: 14 }}>lightbulb</span>
                      {item}
                    </li>
                  ))}
                </ul>
              </div>

              {/* Structure */}
              <div className="bg-white rounded-2xl border border-slate-200 p-4">
                <div className="flex items-center gap-2 mb-2">
                  <div className="w-2 h-2 rounded-full bg-blue-500" />
                  <span className="text-sm font-bold text-slate-800">Cấu trúc</span>
                </div>
                <p className="text-xs text-slate-600">{feedback.structure}</p>
              </div>

              {/* Improved version */}
              <div className="bg-white rounded-2xl border border-slate-200 p-4">
                <button
                  onClick={() => setImprovedExpanded((v) => !v)}
                  className="w-full flex items-center justify-between"
                >
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-green-500" />
                    <span className="text-sm font-bold text-slate-800">Bài viết cải thiện</span>
                  </div>
                  <span className="material-symbols-outlined text-slate-400" style={{ fontSize: 18 }}>
                    {improvedExpanded ? 'expand_less' : 'expand_more'}
                  </span>
                </button>
                {improvedExpanded && (
                  <p className="mt-3 text-xs text-slate-600 leading-relaxed border-t border-slate-100 pt-3">
                    {feedback.improvedVersion}
                  </p>
                )}
              </div>

              {/* Summary */}
              <div className="bg-green-50 rounded-2xl border border-green-100 p-4">
                <div className="flex items-center gap-2 mb-2">
                  <span className="material-symbols-outlined text-green-600" style={{ fontSize: 16 }}>summarize</span>
                  <span className="text-sm font-bold text-green-700">Tổng nhận xét</span>
                </div>
                <p className="text-xs text-slate-600">{feedback.summary}</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
