'use client';

import React, { useState } from 'react';
import { FileText, MessageCircle, Award, Clock, Download, ExternalLink, User, ThumbsUp, Reply, Send, CheckCircle, AlertCircle, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { cn } from '@/utils/cn';

interface Material {
  id: string | number;
  title: string;
  type: 'pdf' | 'doc' | 'docx' | 'ppt' | 'pptx' | 'video' | 'link';
  url: string;
  size?: string;
  description?: string;
}

interface Discussion {
  id: string | number;
  author: string;
  avatar?: string;
  message: string;
  replies: number;
  time: string;
  likes?: number;
  isLiked?: boolean;
}

interface Quiz {
  id: string;
  title: string;
  questions: number;
  duration: number; // in minutes
  attempts: number;
  maxAttempts?: number;
  passingScore?: number;
  lastScore?: number;
  status?: 'not_started' | 'in_progress' | 'completed' | 'passed' | 'failed';
}

interface Assignment {
  id: string;
  title: string;
  description?: string;
  dueDate: string;
  maxScore?: number;
  submitted: boolean;
  submittedAt?: string;
  score?: number;
  feedback?: string;
  status?: 'not_submitted' | 'submitted' | 'graded' | 'late';
  attachments?: {
    id: string;
    name: string;
    size: string;
    type: string;
  }[];
}

interface ModuleTabsProps {
  materials: Material[];
  discussions: Discussion[];
  quiz?: Quiz | null;
  assignment?: Assignment | null;
  onQuizStart?: (quizId: string) => void;
  onAssignmentSubmit?: (assignmentId: string, files: File[]) => void;
  onDiscussionPost?: (message: string) => void;
  onDiscussionReply?: (discussionId: string | number, message: string) => void;
  onDiscussionLike?: (discussionId: string | number) => void;
}

export default function ModuleTabs({
  materials,
  discussions,
  quiz,
  assignment,
  onQuizStart,
  onAssignmentSubmit,
  onDiscussionPost,
  onDiscussionReply,
  onDiscussionLike
}: ModuleTabsProps) {
  const [activeTab, setActiveTab] = useState('materials');
  const [newDiscussion, setNewDiscussion] = useState('');
  const [replyingTo, setReplyingTo] = useState<string | number | null>(null);
  const [replyMessage, setReplyMessage] = useState('');
  const [assignmentFiles, setAssignmentFiles] = useState<File[]>([]);

  const getFileIcon = (type: string) => {
    switch (type.toLowerCase()) {
      case 'pdf':
        return '📄';
      case 'doc':
      case 'docx':
        return '📝';
      case 'ppt':
      case 'pptx':
        return '📊';
      case 'video':
        return '🎥';
      case 'link':
        return '🔗';
      default:
        return '📁';
    }
  };

  const formatFileSize = (size: string) => {
    return size;
  };

  const formatTimeAgo = (time: string) => {
    return time;
  };

  const handleDiscussionSubmit = () => {
    if (newDiscussion.trim()) {
      onDiscussionPost?.(newDiscussion);
      setNewDiscussion('');
    }
  };

  const handleReplySubmit = (discussionId: string | number) => {
    if (replyMessage.trim()) {
      onDiscussionReply?.(discussionId, replyMessage);
      setReplyMessage('');
      setReplyingTo(null);
    }
  };

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    setAssignmentFiles(prev => [...prev, ...files]);
  };

  const removeFile = (index: number) => {
    setAssignmentFiles(prev => prev.filter((_, i) => i !== index));
  };

  const handleAssignmentSubmit = () => {
    if (assignment && assignmentFiles.length > 0) {
      onAssignmentSubmit?.(assignment.id, assignmentFiles);
      setAssignmentFiles([]);
    }
  };

  const getQuizStatusColor = (status?: string) => {
    switch (status) {
      case 'passed':
        return 'bg-green-100 text-green-800';
      case 'failed':
        return 'bg-red-100 text-red-800';
      case 'in_progress':
        return 'bg-yellow-100 text-yellow-800';
      case 'completed':
        return 'bg-blue-100 text-blue-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getAssignmentStatusColor = (status?: string) => {
    switch (status) {
      case 'graded':
        return 'bg-green-100 text-green-800';
      case 'submitted':
        return 'bg-blue-100 text-blue-800';
      case 'late':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  return (
    <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
      <TabsList className="grid w-full grid-cols-4">
        <TabsTrigger value="materials" className="flex items-center gap-2">
          <FileText className="w-4 h-4" />
          Materi
        </TabsTrigger>
        <TabsTrigger value="discussions" className="flex items-center gap-2">
          <MessageCircle className="w-4 h-4" />
          Diskusi
          {discussions.length > 0 && (
            <Badge variant="secondary" className="ml-1 text-xs">
              {discussions.length}
            </Badge>
          )}
        </TabsTrigger>
        <TabsTrigger 
          value="quiz" 
          className={cn(
            "flex items-center gap-2",
            !quiz && "opacity-50 pointer-events-none"
          )}
        >
          <Award className="w-4 h-4" />
          Kuis
        </TabsTrigger>
        <TabsTrigger 
          value="assignment" 
          className={cn(
            "flex items-center gap-2",
            !assignment && "opacity-50 pointer-events-none"
          )}
        >
          <Upload className="w-4 h-4" />
          Tugas
        </TabsTrigger>
      </TabsList>

      {/* Materials Tab */}
      <TabsContent value="materials" className="mt-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="w-5 h-5" />
              Materi Pendukung
            </CardTitle>
            <CardDescription>
              Download materi pembelajaran untuk referensi offline
            </CardDescription>
          </CardHeader>
          <CardContent>
            {materials.length > 0 ? (
              <div className="space-y-4">
                {materials.map((material) => (
                  <div key={material.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                    <div className="flex items-center gap-4">
                      <div className="text-2xl">{getFileIcon(material.type)}</div>
                      <div>
                        <h4 className="font-medium text-gray-900">{material.title}</h4>
                        {material.description && (
                          <p className="text-sm text-gray-600 mt-1">{material.description}</p>
                        )}
                        <div className="flex items-center gap-4 mt-2 text-xs text-gray-500">
                          <span className="uppercase font-medium">{material.type}</span>
                          {material.size && <span>{formatFileSize(material.size)}</span>}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      {material.type === 'link' ? (
                        <Button 
                          size="sm" 
                          variant="outline" 
                          onClick={() => window.open(material.url, '_blank', 'noopener,noreferrer')}
                        >
                          <ExternalLink className="w-4 h-4 mr-2" />
                          Buka
                        </Button>
                      ) : (
                        <Button 
                          size="sm" 
                          variant="outline" 
                          onClick={() => {
                            const link = document.createElement('a');
                            link.href = material.url;
                            link.download = '';
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                          }}
                        >
                          <Download className="w-4 h-4 mr-2" />
                          Download
                        </Button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <FileText className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                <p>Belum ada materi yang tersedia</p>
              </div>
            )}
          </CardContent>
        </Card>
      </TabsContent>

      {/* Discussions Tab */}
      <TabsContent value="discussions" className="mt-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MessageCircle className="w-5 h-5" />
              Forum Diskusi
            </CardTitle>
            <CardDescription>
              Diskusikan materi dengan sesama peserta dan instruktur
            </CardDescription>
          </CardHeader>
          <CardContent>
            {/* New Discussion Form */}
            <div className="mb-6 p-4 bg-blue-50 rounded-lg">
              <h4 className="font-medium text-gray-900 mb-3">Mulai Diskusi Baru</h4>
              <Textarea
                placeholder="Tulis pertanyaan atau topik diskusi..."
                value={newDiscussion}
                onChange={(e) => setNewDiscussion(e.target.value)}
                className="mb-3"
              />
              <Button onClick={handleDiscussionSubmit} disabled={!newDiscussion.trim()}>
                <Send className="w-4 h-4 mr-2" />
                Kirim Diskusi
              </Button>
            </div>

            {/* Discussions List */}
            {discussions.length > 0 ? (
              <div className="space-y-4">
                {discussions.map((discussion) => (
                  <div key={discussion.id} className="p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                          <User className="w-5 h-5 text-blue-600" />
                        </div>
                        <div>
                          <h5 className="font-medium text-gray-900">{discussion.author}</h5>
                          <p className="text-sm text-gray-500">{formatTimeAgo(discussion.time)}</p>
                        </div>
                      </div>
                    </div>
                    
                    <p className="text-gray-700 mb-4">{discussion.message}</p>
                    
                    <div className="flex items-center gap-4 text-sm">
                      <button 
                        onClick={() => onDiscussionLike?.(discussion.id)}
                        className={cn(
                          "flex items-center gap-1 px-3 py-1 rounded-full transition-colors",
                          discussion.isLiked 
                            ? "bg-blue-100 text-blue-700" 
                            : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                        )}
                      >
                        <ThumbsUp className="w-4 h-4" />
                        {discussion.likes || 0}
                      </button>
                      
                      <button 
                        onClick={() => setReplyingTo(discussion.id)}
                        className="flex items-center gap-1 px-3 py-1 rounded-full bg-gray-100 text-gray-600 hover:bg-gray-200 transition-colors"
                      >
                        <Reply className="w-4 h-4" />
                        {discussion.replies} Balasan
                      </button>
                    </div>
                    
                    {/* Reply Form */}
                    {replyingTo === discussion.id && (
                      <div className="mt-4 p-3 bg-white rounded-lg border">
                        <Textarea
                          placeholder="Tulis balasan..."
                          value={replyMessage}
                          onChange={(e) => setReplyMessage(e.target.value)}
                          className="mb-2"
                          rows={3}
                        />
                        <div className="flex gap-2">
                          <Button 
                            size="sm" 
                            onClick={() => handleReplySubmit(discussion.id)}
                            disabled={!replyMessage.trim()}
                          >
                            Kirim Balasan
                          </Button>
                          <Button 
                            size="sm" 
                            variant="outline" 
                            onClick={() => setReplyingTo(null)}
                          >
                            Batal
                          </Button>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <MessageCircle className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                <p>Belum ada diskusi. Mulai diskusi pertama!</p>
              </div>
            )}
          </CardContent>
        </Card>
      </TabsContent>

      {/* Quiz Tab */}
      <TabsContent value="quiz" className="mt-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Award className="w-5 h-5" />
              Kuis Modul
            </CardTitle>
            <CardDescription>
              Uji pemahaman Anda dengan kuis interaktif
            </CardDescription>
          </CardHeader>
          <CardContent>
            {quiz ? (
              <div className="space-y-6">
                <div className="p-6 bg-blue-50 rounded-lg">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <h4 className="text-xl font-semibold text-gray-900 mb-2">{quiz.title}</h4>
                      <div className="space-y-2 text-sm text-gray-600">
                        <div className="flex items-center gap-4">
                          <span className="flex items-center gap-1">
                            <Award className="w-4 h-4" />
                            {quiz.questions} soal
                          </span>
                          <span className="flex items-center gap-1">
                            <Clock className="w-4 h-4" />
                            {quiz.duration} menit
                          </span>
                        </div>
                        <div className="flex items-center gap-4">
                          <span>Percobaan: {quiz.attempts}/{quiz.maxAttempts || '∞'}</span>
                          {quiz.passingScore && (
                            <span>Nilai lulus: {quiz.passingScore}%</span>
                          )}
                        </div>
                      </div>
                    </div>
                    {quiz.status && (
                      <Badge className={getQuizStatusColor(quiz.status)}>
                        {quiz.status === 'passed' && 'Lulus'}
                        {quiz.status === 'failed' && 'Tidak Lulus'}
                        {quiz.status === 'completed' && 'Selesai'}
                        {quiz.status === 'in_progress' && 'Sedang Dikerjakan'}
                        {quiz.status === 'not_started' && 'Belum Dimulai'}
                      </Badge>
                    )}
                  </div>
                  
                  {quiz.lastScore !== undefined && (
                    <div className="mb-4 p-3 bg-white rounded-lg">
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-gray-600">Nilai Terakhir:</span>
                        <span className={cn(
                          "font-semibold",
                          quiz.lastScore >= (quiz.passingScore || 70) ? "text-green-600" : "text-red-600"
                        )}>
                          {quiz.lastScore}%
                        </span>
                      </div>
                    </div>
                  )}
                  
                  <div className="flex gap-3">
                    <Button 
                      onClick={() => onQuizStart?.(quiz.id)}
                      disabled={quiz.status === 'in_progress' || (quiz.maxAttempts != null && quiz.attempts >= quiz.maxAttempts)}
                      className="flex-1"
                    >
                      {quiz.status === 'not_started' ? 'Mulai Kuis' : 
                       quiz.status === 'in_progress' ? 'Lanjutkan Kuis' : 
                       'Ulangi Kuis'}
                    </Button>
                    {quiz.status === 'in_progress' && (
                      <Button variant="outline">
                        Lanjutkan
                      </Button>
                    )}
                  </div>
                </div>
                
                {/* Quiz Instructions */}
                <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                  <div className="flex items-start gap-2">
                    <AlertCircle className="w-5 h-5 text-yellow-600 mt-0.5" />
                    <div>
                      <h5 className="font-medium text-yellow-800 mb-2">Petunjuk Kuis:</h5>
                      <ul className="text-sm text-yellow-700 space-y-1">
                        <li>• Pastikan koneksi internet stabil</li>
                        <li>• Kuis akan otomatis tersimpan setiap 30 detik</li>
                        <li>• Anda dapat kembali ke soal sebelumnya</li>
                        <li>• Waktu akan terus berjalan meskipun tab ditutup</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <Award className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                <p>Kuis tidak tersedia untuk modul ini</p>
              </div>
            )}
          </CardContent>
        </Card>
      </TabsContent>

      {/* Assignment Tab */}
      <TabsContent value="assignment" className="mt-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Upload className="w-5 h-5" />
              Tugas Modul
            </CardTitle>
            <CardDescription>
              Kerjakan dan submit tugas untuk menyelesaikan modul
            </CardDescription>
          </CardHeader>
          <CardContent>
            {assignment ? (
              <div className="space-y-6">
                <div className="p-6 bg-green-50 rounded-lg">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <h4 className="text-xl font-semibold text-gray-900 mb-2">{assignment.title}</h4>
                      {assignment.description && (
                        <p className="text-gray-600 mb-4">{assignment.description}</p>
                      )}
                      <div className="space-y-2 text-sm text-gray-600">
                        <div className="flex items-center gap-4">
                          <span className="flex items-center gap-1">
                            <Clock className="w-4 h-4" />
                            Batas waktu: {assignment.dueDate}
                          </span>
                          {assignment.maxScore && (
                            <span>Nilai maksimal: {assignment.maxScore}</span>
                          )}
                        </div>
                        <div className={cn(
                          "font-medium",
                          assignment.submitted ? "text-green-600" : "text-orange-600"
                        )}>
                          Status: {assignment.submitted ? 'Sudah dikumpulkan' : 'Belum dikumpulkan'}
                        </div>
                      </div>
                    </div>
                    {assignment.status && (
                      <Badge className={getAssignmentStatusColor(assignment.status)}>
                        {assignment.status === 'graded' && 'Sudah Dinilai'}
                        {assignment.status === 'submitted' && 'Sudah Dikumpulkan'}
                        {assignment.status === 'late' && 'Terlambat'}
                        {assignment.status === 'not_submitted' && 'Belum Dikumpulkan'}
                      </Badge>
                    )}
                  </div>
                  
                  {/* Score and Feedback */}
                  {assignment.score !== undefined && (
                    <div className="mb-4 p-4 bg-white rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <span className="font-medium text-gray-900">Nilai:</span>
                        <span className="text-lg font-bold text-green-600">
                          {assignment.score}/{assignment.maxScore || 100}
                        </span>
                      </div>
                      {assignment.feedback && (
                        <div>
                          <span className="font-medium text-gray-900 block mb-1">Feedback:</span>
                          <p className="text-gray-600 text-sm">{assignment.feedback}</p>
                        </div>
                      )}
                    </div>
                  )}
                  
                  {/* Submitted Files */}
                  {assignment.attachments && assignment.attachments.length > 0 && (
                    <div className="mb-4">
                      <h5 className="font-medium text-gray-900 mb-2">File yang Dikumpulkan:</h5>
                      <div className="space-y-2">
                        {assignment.attachments.map((file) => (
                          <div key={file.id} className="flex items-center gap-3 p-2 bg-white rounded border">
                            <div className="text-lg">{getFileIcon(file.type)}</div>
                            <div className="flex-1">
                              <p className="font-medium text-sm">{file.name}</p>
                              <p className="text-xs text-gray-500">{file.size}</p>
                            </div>
                            <Button size="sm" variant="outline">
                              <Download className="w-4 h-4" />
                            </Button>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                  
                  {/* File Upload Section */}
                  {!assignment.submitted && (
                    <div className="space-y-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          Upload File Tugas
                        </label>
                        <Input
                          type="file"
                          multiple
                          onChange={handleFileUpload}
                          className="mb-2"
                          accept=".pdf,.doc,.docx,.ppt,.pptx,.zip,.rar"
                        />
                        <p className="text-xs text-gray-500">
                          Format yang didukung: PDF, DOC, DOCX, PPT, PPTX, ZIP, RAR (Max 10MB per file)
                        </p>
                      </div>
                      
                      {/* Selected Files */}
                      {assignmentFiles.length > 0 && (
                        <div>
                          <h6 className="font-medium text-gray-900 mb-2">File yang Dipilih:</h6>
                          <div className="space-y-2">
                            {assignmentFiles.map((file, index) => (
                              <div key={index} className="flex items-center gap-3 p-2 bg-white rounded border">
                                <div className="text-lg">📄</div>
                                <div className="flex-1">
                                  <p className="font-medium text-sm">{file.name}</p>
                                  <p className="text-xs text-gray-500">{(file.size / 1024 / 1024).toFixed(2)} MB</p>
                                </div>
                                <Button 
                                  size="sm" 
                                  variant="outline" 
                                  onClick={() => removeFile(index)}
                                >
                                  Hapus
                                </Button>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                      
                      <Button 
                        onClick={handleAssignmentSubmit}
                        disabled={assignmentFiles.length === 0}
                        className="w-full"
                      >
                        <Upload className="w-4 h-4 mr-2" />
                        Kumpulkan Tugas
                      </Button>
                    </div>
                  )}
                  
                  {assignment.submitted && (
                    <div className="flex items-center gap-2 p-3 bg-green-100 rounded-lg">
                      <CheckCircle className="w-5 h-5 text-green-600" />
                      <span className="text-green-800 font-medium">
                        Tugas berhasil dikumpulkan pada {assignment.submittedAt}
                      </span>
                    </div>
                  )}
                </div>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <Upload className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                <p>Tidak ada tugas untuk modul ini</p>
              </div>
            )}
          </CardContent>
        </Card>
      </TabsContent>
    </Tabs>
  );
}