"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import {
  Clock,
  Paperclip,
  Download,
  Send,
  CheckCircle2,
  AlertTriangle,
  FileText,
  ExternalLink,
  Award,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { formatDateID, formatBytes, getDeadlineStatus } from "@/lib/utils";

interface StudentAssignmentSubmitClientProps {
  assignment: any;
  existingSubmission: any | null;
}

export default function StudentAssignmentSubmitClient({
  assignment,
  existingSubmission,
}: StudentAssignmentSubmitClientProps) {
  const router = useRouter();
  const [content, setContent] = React.useState(existingSubmission?.content || "");
  const [linkUrl, setLinkUrl] = React.useState(existingSubmission?.linkUrl || "");
  const [fileToUpload, setFileToUpload] = React.useState<File | null>(null);
  const [isLoading, setIsLoading] = React.useState(false);
  const [successMsg, setSuccessMsg] = React.useState("");
  const [errorMsg, setErrorMsg] = React.useState("");

  const deadline = getDeadlineStatus(assignment.dueDate);

  const handleSubmitAssignment = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setErrorMsg("");
    setSuccessMsg("");

    try {
      let attachments: any[] = [];
      if (fileToUpload) {
        const formData = new FormData();
        formData.append("file", fileToUpload);
        formData.append("folder", "submissions");
        const uploadRes = await fetch("/api/upload", {
          method: "POST",
          body: formData,
        });
        const uploadData = await uploadRes.json();
        if (uploadData.success) {
          attachments.push(uploadData.data);
        }
      }

      const res = await fetch(`/api/assignments/${assignment.id}/submit`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          content,
          linkUrl,
          attachments,
        }),
      });

      const data = await res.json();
      setIsLoading(false);
      if (res.ok && data.success) {
        setSuccessMsg(data.message || "Tugas berhasil dikirim!");
        window.location.reload();
      } else {
        setErrorMsg(data.error || "Gagal mengirim tugas.");
      }
    } catch (err) {
      setIsLoading(false);
      setErrorMsg("Terjadi gangguan koneksi server.");
    }
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      {/* LEFT 2 COLS: Assignment Instructions & Teacher Attachments */}
      <div className="lg:col-span-2 space-y-6">
        <Card>
          <CardHeader className="pb-3 border-b border-slate-100">
            <div className="flex items-center justify-between">
              <Badge variant="primary">
                {assignment.teacherSubject.subject.name}
              </Badge>
              <span
                className={`text-xs font-bold px-2.5 py-0.5 rounded-full border ${deadline.badgeClass}`}
              >
                {deadline.label}
              </span>
            </div>
            <CardTitle className="text-xl mt-2 text-slate-900">
              {assignment.title}
            </CardTitle>
            <div className="flex flex-wrap items-center gap-4 text-xs text-slate-500 pt-1">
              <span className="flex items-center gap-1 font-mono">
                <Clock className="h-3.5 w-3.5 text-slate-400" />
                Batas Akhir: {formatDateID(assignment.dueDate, true)}
              </span>
              <span>Skor Maks: {assignment.maxScore}</span>
            </div>
          </CardHeader>

          <CardContent className="space-y-4 pt-4">
            {assignment.description && (
              <div className="p-3.5 rounded-xl bg-blue-50/60 border border-blue-100 text-blue-900 text-xs font-medium leading-relaxed">
                {assignment.description}
              </div>
            )}

            {assignment.instructions && (
              <div className="space-y-1.5 text-xs text-slate-700">
                <h4 className="font-bold text-slate-900">Petunjuk Pengerjaan:</h4>
                <div className="p-4 rounded-xl bg-slate-50 border border-slate-200 whitespace-pre-wrap leading-relaxed">
                  {assignment.instructions}
                </div>
              </div>
            )}

            {/* Lampiran Soal dari Guru */}
            {assignment.attachments?.length > 0 && (
              <div className="space-y-2 pt-2 border-t border-slate-100">
                <h4 className="text-xs font-bold text-slate-900">
                  Dokumen Soal & Lembar Kerja (LKPD):
                </h4>
                {assignment.attachments.map((att: any) => (
                  <div
                    key={att.id}
                    className="flex items-center justify-between p-3 rounded-xl border border-slate-200 bg-white"
                  >
                    <div className="flex items-center gap-2.5 truncate">
                      <Paperclip className="h-4 w-4 text-blue-500 shrink-0" />
                      <span className="text-xs font-semibold text-slate-800 truncate">
                        {att.fileName}
                      </span>
                      <span className="text-[10px] text-slate-400 font-mono">
                        ({formatBytes(att.fileSize)})
                      </span>
                    </div>
                    <a
                      href={att.filePath}
                      target="_blank"
                      rel="noreferrer"
                      className="p-1.5 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 text-xs font-bold flex items-center gap-1 shrink-0"
                    >
                      <Download className="h-3.5 w-3.5" />
                      Unduh Soal
                    </a>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Existing Submission Details if already graded */}
        {existingSubmission?.status === "GRADED" && (
          <Card className="border-emerald-200 bg-emerald-50/20">
            <CardHeader className="pb-2">
              <div className="flex items-center gap-2">
                <Award className="h-5 w-5 text-emerald-600" />
                <CardTitle className="text-emerald-900">
                  Hasil Penilaian & Evaluasi Guru
                </CardTitle>
              </div>
            </CardHeader>
            <CardContent className="space-y-3 pt-2">
              <div className="flex items-center justify-between p-4 rounded-xl bg-white border border-emerald-200 shadow-sm">
                <div>
                  <span className="text-xs text-slate-500">Nilai Akhir Tugas</span>
                  <p className="text-3xl font-black text-emerald-600">
                    {existingSubmission.score} / {assignment.maxScore}
                  </p>
                </div>
                <Badge variant="success">Tuntas</Badge>
              </div>

              {existingSubmission.feedback && (
                <div className="p-3.5 rounded-xl bg-white border border-slate-200 text-xs text-slate-700 space-y-1">
                  <span className="font-bold text-slate-900">Catatan Feedback Guru:</span>
                  <p className="italic text-slate-600">"{existingSubmission.feedback}"</p>
                </div>
              )}
            </CardContent>
          </Card>
        )}
      </div>

      {/* RIGHT COLUMN: Submission Form */}
      <div className="space-y-6">
        <Card>
          <CardHeader className="pb-3 border-b border-slate-100">
            <CardTitle>Lembar Pengumpulan Tugas</CardTitle>
            <p className="text-xs text-slate-500">
              {existingSubmission
                ? `Terkirim: ${formatDateID(existingSubmission.submittedAt, true)}`
                : "Kirimkan jawaban tugas Anda sebelum batas waktu."}
            </p>
          </CardHeader>

          <CardContent className="pt-4">
            {successMsg && (
              <div className="p-3 mb-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-700 text-xs font-semibold">
                {successMsg}
              </div>
            )}
            {errorMsg && (
              <div className="p-3 mb-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-700 text-xs font-semibold">
                {errorMsg}
              </div>
            )}

            <form onSubmit={handleSubmitAssignment} className="space-y-4">
              {/* Teks Jawaban */}
              {(assignment.submissionType === "TEXT" ||
                assignment.submissionType === "COMBINATION") && (
                <Textarea
                  label="Teks Jawaban / Ringkasan Online"
                  placeholder="Ketik jawaban tugas atau uraian penjelasan Anda di sini..."
                  rows={5}
                  value={content}
                  onChange={(e) => setContent(e.target.value)}
                />
              )}

              {/* Tautan Link */}
              {(assignment.submissionType === "LINK" ||
                assignment.submissionType === "COMBINATION") && (
                <Input
                  label="Tautan Link (Google Drive / GitHub / Video)"
                  placeholder="https://drive.google.com/..."
                  value={linkUrl}
                  onChange={(e) => setLinkUrl(e.target.value)}
                />
              )}

              {/* File Attachment */}
              {(assignment.submissionType === "FILE" ||
                assignment.submissionType === "COMBINATION") && (
                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1">
                    Unggah Berkas Jawaban (PDF / Word / Gambar / ZIP)
                  </label>
                  <input
                    type="file"
                    onChange={(e) => setFileToUpload(e.target.files?.[0] || null)}
                    className="w-full text-xs text-slate-500 file:mr-3 file:py-2 file:px-3 file:rounded-xl file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                  />
                </div>
              )}

              {/* Existing file preview */}
              {existingSubmission?.attachments?.length > 0 && !fileToUpload && (
                <div className="p-2.5 rounded-lg bg-slate-50 border border-slate-200 text-xs">
                  <span className="text-[10px] text-slate-500 block">Berkas sebelumnya terunggah:</span>
                  <span className="font-semibold text-slate-800">
                    {existingSubmission.attachments[0].fileName}
                  </span>
                </div>
              )}

              <Button
                type="submit"
                size="md"
                className="w-full font-bold text-xs"
                isLoading={isLoading}
              >
                <Send className="mr-1.5 h-3.5 w-3.5" />
                {existingSubmission ? "Perbarui Kiriman Jawaban" : "Kirimkan Tugas Sekarang"}
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
