"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Upload, Download, Users, FileSpreadsheet } from "lucide-react";
import { toast } from "sonner";

export function SiswaBaru() {
  const [file, setFile] = React.useState<File | null>(null);
  const [uploading, setUploading] = React.useState(false);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = event.target.files?.[0];
    if (selectedFile) {
      // Validasi file Excel
      const allowedTypes = [
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.ms-excel",
      ];

      if (!allowedTypes.includes(selectedFile.type)) {
        toast.error("File harus berformat Excel (.xlsx atau .xls)");
        return;
      }

      setFile(selectedFile);
      toast.success(`File ${selectedFile.name} dipilih`);
    }
  };

  const handleUpload = async () => {
    if (!file) {
      toast.error("Pilih file terlebih dahulu");
      return;
    }

    setUploading(true);
    const formData = new FormData();
    formData.append("file", file);

    try {
      const response = await fetch("/api/siswa/import", {
        method: "POST",
        body: formData,
      });

      const result = await response.json();

      if (result.success) {
        toast.success(`Berhasil mengimpor ${result.imported} siswa baru`);
        setFile(null);
        // Reset file input
        const fileInput = document.getElementById("file-input") as HTMLInputElement;
        if (fileInput) fileInput.value = "";

        if (result.errors && result.errors.length > 0) {
          toast.warning(`${result.errors.length} data memiliki error, silakan periksa log`);
        }
      } else {
        toast.error(result.error || "Gagal mengimpor data siswa");
      }
    } catch (error) {
      console.error("Error uploading file:", error);
      toast.error("Terjadi kesalahan saat mengupload file");
    } finally {
      setUploading(false);
    }
  };

  const downloadTemplate = () => {
    // Download template Excel
    const link = document.createElement("a");
    link.href = "/template_siswa.xlsx"; // File template harus ada di public folder
    link.download = "template_siswa_baru.xlsx";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Users className="h-5 w-5" />
            Import Siswa Baru
          </CardTitle>
          <CardDescription>Upload file Excel untuk menambahkan siswa baru ke sistem</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="grid gap-6 md:grid-cols-2">
            <div className="space-y-4">
              <div>
                <Label htmlFor="file-input">File Excel Siswa</Label>
                <div className="mt-2">
                  <Input
                    id="file-input"
                    type="file"
                    accept=".xlsx,.xls"
                    onChange={handleFileChange}
                    className="file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 file:mr-4 file:rounded-md file:border-0 file:px-4 file:py-2 file:text-sm"
                  />
                </div>
                {file && <p className="text-muted-foreground mt-1 text-sm">File terpilih: {file.name}</p>}
              </div>

              <Button onClick={handleUpload} disabled={!file || uploading} className="w-full">
                {uploading ? (
                  <>
                    <Upload className="mr-2 h-4 w-4 animate-pulse" />
                    Mengupload...
                  </>
                ) : (
                  <>
                    <Upload className="mr-2 h-4 w-4" />
                    Upload Data Siswa
                  </>
                )}
              </Button>
            </div>

            <div className="space-y-4">
              <div>
                <Label>Template Excel</Label>
                <p className="text-muted-foreground mt-1 mb-3 text-sm">
                  Download template untuk format data siswa yang benar
                </p>
                <Button variant="outline" onClick={downloadTemplate} className="w-full">
                  <Download className="mr-2 h-4 w-4" />
                  Download Template
                </Button>
              </div>
            </div>
          </div>

          <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
            <div className="flex gap-3">
              <FileSpreadsheet className="mt-0.5 h-5 w-5 text-blue-600" />
              <div className="space-y-1">
                <h4 className="text-sm font-medium text-blue-900">Format File Excel</h4>
                <div className="space-y-1 text-sm text-blue-800">
                  <p>File Excel harus mengandung kolom-kolom berikut:</p>
                  <ul className="ml-2 list-inside list-disc space-y-0.5">
                    <li>
                      <strong>username</strong> - Username untuk login (wajib)
                    </li>
                    <li>
                      <strong>password</strong> - Password untuk login (wajib)
                    </li>
                    <li>
                      <strong>name</strong> - Nama lengkap siswa (wajib)
                    </li>
                    <li>
                      <strong>nisn</strong> - Nomor Induk Siswa Nasional (wajib)
                    </li>
                    <li>
                      <strong>kelas</strong> - Kelas siswa (wajib)
                    </li>
                    <li>
                      <strong>email</strong> - Email siswa (opsional)
                    </li>
                    <li>
                      <strong>jurusanId</strong> - ID Jurusan (opsional)
                    </li>
                  </ul>
                  <p className="mt-2 text-xs">
                    * Jika email tidak diisi, sistem akan generate otomatis berdasarkan NISN
                  </p>
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Tips Import Siswa Baru</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <h4 className="mb-2 font-medium">Sebelum Upload:</h4>
              <ul className="text-muted-foreground space-y-1 text-sm">
                <li>• Pastikan format file adalah .xlsx atau .xls</li>
                <li>• Periksa semua data wajib sudah terisi</li>
                <li>• Username harus unik (tidak boleh sama)</li>
                <li>• NISN harus unik dan berupa angka</li>
              </ul>
            </div>
            <div>
              <h4 className="mb-2 font-medium">Setelah Upload:</h4>
              <ul className="text-muted-foreground space-y-1 text-sm">
                <li>• Sistem akan validasi setiap baris data</li>
                <li>• Data yang error akan dilewati</li>
                <li>• Siswa baru akan mendapat status AKTIF</li>
                <li>• Password akan di-hash otomatis untuk keamanan</li>
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
