'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { useT } from '@/i18n';
import { API_BASE } from '@/lib/config';
import { useAuth } from '@/lib/auth-context';
import { apiFetch, getToken } from '@/lib/auth';
import { Lightbulb, CheckCircle, Clock, BarChart3 } from 'lucide-react';

interface PracticeQuestion {
  id: number;
  skillId: string | null;
  scenario: string;
  title: string;
  description: string;
  instructions: string;
  difficulty: string;
  category: string;
  expectedCriteria: string;
  starterCode: string | null;
  hint: string | null;
}

interface CriteriaScore {
  name: string;
  score: number;
  maxScore: number;
  reason: string;
}

interface Submission {
  id: number;
  questionId: number;
  answer: string;
  score: number | null;
  maxScore: number;
  feedback: string | null;
  criteriaScores: string | null;
  duration: number;
  status: string;
  submittedAt: string;
  scoredAt: string | null;
  question: PracticeQuestion;
}

export default function PracticeDetailPage() {
  const params = useParams();
  const t = useT();
  const { isLoggedIn } = useAuth();
  const [question, setQuestion] = useState<PracticeQuestion | null>(null);
  const [loading, setLoading] = useState(true);
  const [answer, setAnswer] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [submission, setSubmission] = useState<Submission | null>(null);
  const [showHint, setShowHint] = useState(false);
  const [startTime] = useState(Date.now());

  useEffect(() => {
    if (!params.id) return;
    fetch(`${API_BASE}/practices/${params.id}`)
      .then(r => r.json())
      .then(data => {
        if (data.id) setQuestion(data);
      })
      .finally(() => setLoading(false));
  }, [params.id]);

  useEffect(() => {
    if (!isLoggedIn || !params.id) return;
    apiFetch(`/practices/submissions?limit=50`)
      .then(r => r.json())
      .then(data => {
        const found = (data.items || []).find((s: any) => s.questionId === Number(params.id));
        if (found) setSubmission(found);
      })
      .catch(() => {});
  }, [isLoggedIn, params.id]);

  const handleSubmit = async () => {
    if (!answer.trim() || !isLoggedIn) return;
    setSubmitting(true);
    try {
      const duration = Math.floor((Date.now() - startTime) / 1000);
      const res = await apiFetch(`/practices/${params.id}/submit`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ answer: answer.trim(), duration }),
      });
      if (res.ok) {
        const data = await res.json();
        setSubmission(data);
      } else {
        const err = await res.json();
        alert(err.message || '提交失败');
      }
    } catch (err: any) {
      alert(err.message || '提交失败');
    } finally {
      setSubmitting(false);
    }
  };

  const difficultyColor = question?.difficulty === 'BEGINNER' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
    : question?.difficulty === 'INTERMEDIATE' ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400'
    : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400';

  if (loading) return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Skeleton className="h-8 w-48 mb-6" />
      <Skeleton className="h-64 rounded-2xl mb-6" />
      <Skeleton className="h-48 rounded-2xl" />
    </div>
  );

  if (!question) return (
    <div className="max-w-4xl mx-auto px-4 py-20 text-center">
      <p className="text-muted-foreground">练习题目不存在</p>
      <Link href="/practices" className="text-brand-600 hover:underline text-sm mt-4 inline-block">&larr; {t.practices.title}</Link>
    </div>
  );

  const parsedCriteria: CriteriaScore[] = submission?.criteriaScores ? JSON.parse(submission.criteriaScores) : [];

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Link href="/practices" className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-block">
        &larr; {t.practices.title}
      </Link>

      <div className="bg-card rounded-2xl border border-border p-6 mb-6">
        <div className="flex items-center gap-3 mb-4">
          <span className={`text-xs px-2 py-0.5 rounded-full ${difficultyColor}`}>
            {(t.practices as any)[question.difficulty.toLowerCase()] || question.difficulty}
          </span>
          <span className="text-xs text-muted-foreground">{(t.practices.categories as any)[question.category] || question.category}</span>
        </div>
        <h1 className="text-2xl font-bold text-foreground mb-2">{question.title}</h1>
        <p className="text-muted-foreground mb-4">{question.description}</p>
        <div className="bg-muted/50 rounded-xl p-4 border border-border">
          <h3 className="text-sm font-medium text-foreground mb-2">{t.practices.title} 场景</h3>
          <p className="text-sm text-muted-foreground whitespace-pre-wrap">{question.scenario}</p>
        </div>
      </div>

      <div className="bg-card rounded-2xl border border-border p-6 mb-6">
        <h2 className="font-semibold text-foreground mb-3">{t.practices.title} 要求</h2>
        <p className="text-sm text-muted-foreground whitespace-pre-wrap">{question.instructions}</p>
        {question.hint && (
          <div className="mt-3">
            <button onClick={() => setShowHint(!showHint)}
              className="flex items-center gap-1.5 text-sm text-brand-600 hover:text-brand-700">
              <Lightbulb className="h-4 w-4" />
              {t.practices.hint}
            </button>
            {showHint && <p className="mt-2 text-sm text-muted-foreground bg-muted/50 rounded-xl p-3">{question.hint}</p>}
          </div>
        )}
      </div>

      {submission?.status === 'SCORED' ? (
        <div className="space-y-6">
          <div className="bg-card rounded-2xl border border-border p-6">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-lg font-semibold text-foreground">{t.practices.score}</h2>
              <div className="flex items-center gap-2">
                <span className="text-3xl font-bold text-brand-600">{submission.score}</span>
                <span className="text-muted-foreground">/ {submission.maxScore}</span>
              </div>
            </div>

            <div className="space-y-3 mb-6">
              {parsedCriteria.map((c, i) => (
                <div key={i} className="bg-muted/50 rounded-xl p-4">
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-sm font-medium text-foreground">{c.name}</span>
                    <span className="text-sm text-muted-foreground">{c.score}/{c.maxScore}</span>
                  </div>
                  <div className="w-full bg-muted rounded-full h-2 mb-1">
                    <div className="bg-brand-600 h-2 rounded-full transition-all" style={{ width: `${(c.score / c.maxScore) * 100}%` }} />
                  </div>
                  <p className="text-xs text-muted-foreground">{c.reason}</p>
                </div>
              ))}
            </div>

            {submission.feedback && (
              <div className="bg-muted/50 rounded-xl p-4 border border-border">
                <h3 className="text-sm font-medium text-foreground mb-2">{t.practices.feedback}</h3>
                <p className="text-sm text-muted-foreground whitespace-pre-wrap">{submission.feedback}</p>
              </div>
            )}
          </div>

          <div className="bg-card rounded-2xl border border-border p-6">
            <h2 className="font-semibold text-foreground mb-3">{t.practices.yourAnswer}</h2>
            <p className="text-sm text-muted-foreground whitespace-pre-wrap">{submission.answer}</p>
          </div>

          <div className="flex items-center justify-between text-xs text-muted-foreground">
            <span>{t.practices.duration}: {submission.duration}{t.practices.seconds}</span>
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          {submission?.status === 'SUBMITTED' ? (
            <div className="bg-card rounded-2xl border border-border p-6 text-center">
              <Clock className="h-8 w-8 text-yellow-500 mx-auto mb-2" />
              <p className="text-muted-foreground">AI 评分中，请稍候...</p>
              <Button variant="outline" size="sm" className="mt-4" onClick={() => window.location.reload()}>
                刷新状态
              </Button>
            </div>
          ) : (
            <>
              <div className="bg-card rounded-2xl border border-border p-6">
                <h2 className="font-semibold text-foreground mb-3">{t.practices.yourAnswer}</h2>
                <textarea value={answer} onChange={e => setAnswer(e.target.value)}
                  placeholder={t.practices.answerPlaceholder}
                  className="w-full min-h-[200px] p-4 border border-border rounded-xl bg-background text-foreground text-sm resize-y focus:outline-none focus:ring-2 focus:ring-brand-600"
                />
              </div>

              {isLoggedIn ? (
                <Button onClick={handleSubmit} disabled={submitting || !answer.trim()}
                  className="w-full sm:w-auto">
                  {submitting ? (
                    <span className="flex items-center gap-2">
                      <span className="animate-spin h-4 w-4 border-2 border-white border-t-transparent rounded-full" />
                      {t.practices.submitting}
                    </span>
                  ) : t.practices.submit}
                </Button>
              ) : (
                <div className="bg-muted/50 rounded-xl p-4 text-center border border-border">
                  <p className="text-muted-foreground mb-3">{t.practices.loginRequired}</p>
                  <Button asChild>
                    <Link href="/auth">{t.common.login}</Link>
                  </Button>
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
}
