"use client";

import * as React from "react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Modal } from "@/components/ui/modal";
import { ConfirmModal } from "@/components/common/ConfirmModal";
import { formatDateID } from "@/lib/utils";
import {
  Bell,
  Search,
  Plus,
  Filter,
  Paperclip,
  Trash2,
  Edit2,
  AlertTriangle,
  Send,
  User,
  CheckCircle,
} from "lucide-react";

interface AnnouncementItem {
  id: string;
  title: string;
  content: string;
  priority: "NORMAL" | "IMPORTANT" | "URGENT";
  target: "ALL" | "ALL_STUDENTS" | "ALL_TEACHERS" | "SPECIFIC_CLASS" | "SPECIFIC_SUBJECT";
  targetId?: string | null;
  createdAt: string;
  author: {
    id: string;
    username: string;
    role: string;
    teacher?: { fullName: string; nip?: string | null } | null;
  };
  attachments?: {
    id: string;
    fileName: string;
    fileSize: number;
    filePath: string;
  }[];
}

interface AnnouncementsBoardProps {
  currentUserId: string;
  currentUserRole: "ADMIN" | "TEACHER" | "STUDENT";
  canCreate?: boolean;
}

export function AnnouncementsBoard({
  currentUserId,
  currentUserRole,
  canCreate = false,
}: AnnouncementsBoardProps) {
  const [announcements, setAnnouncements] = React.useState<AnnouncementItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState("");
  const [priorityFilter, setPriorityFilter] = React.useState("ALL");

  // Create / Edit modal state
  const [modalOpen, setModalOpen] = React.useState(false);
  const [editingId, setEditingId] = React.useState<string | null>(null);
  const [title, setTitle] = React.useState("");
  const [content, setContent] = React.useState("");
  const [priority, setPriority] = React.useState<"NORMAL" | "IMPORTANT" | "URGENT">("NORMAL");
  const [target, setTarget] = React.useState<string>("ALL");
  const [submitting, setSubmitting] = React.useState(false);
  const [formError, setFormError] = React.useState("");

  // Delete modal state
  const [deleteTarget, setDeleteTarget] = React.useState<AnnouncementItem | null>(null);
  const [deleting, setDeleting] = React.useState(false);

  const fetchAnnouncements = React.useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch(`/api/announcements?priority=${priorityFilter}&search=${encodeURIComponent(search)}`);
      const data = await res.json();
      if (data.success) {
        setAnnouncements(data.data || []);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [priorityFilter, search]);

  React.useEffect(() => {
    fetchAnnouncements();
  }, [fetchAnnouncements]);

  const handleOpenCreate = () => {
    setEditingId(null);
    setTitle("");
    setContent("");
    setPriority("NORMAL");
    setTarget(currentUserRole === "ADMIN" ? "ALL" : "ALL_STUDENTS");
    setFormError("");
    setModalOpen(true);
  };

  const handleOpenEdit = (a: AnnouncementItem) => {
    setEditingId(a.id);
    setTitle(a.title);
    setContent(a.content);
    setPriority(a.priority);
    setTarget(a.target);
    setFormError("");
    setModalOpen(true);
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim() || !content.trim()) {
      setFormError("Judul dan isi pengumuman wajib diisi.");
      return;
    }

    try {
      setSubmitting(true);
      setFormError("");

      const url = editingId ? `/api/announcements/${editingId}` : "/api/announcements";
      const method = editingId ? "PUT" : "POST";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title,
          content,
          priority,
          target,
        }),
      });

      const data = await res.json();
      if (data.success) {
        setModalOpen(false);
        fetchAnnouncements();
      } else {
        setFormError(data.error || "Gagal menyimpan pengumuman.");
      }
    } catch (err) {
      setFormError("Terjadi kesalahan jaringan.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      setDeleting(true);
      const res = await fetch(`/api/announcements/${deleteTarget.id}`, { method: "DELETE" });
      const data = await res.json();
      if (data.success) {
        setDeleteTarget(null);
        fetchAnnouncements();
      }
    } catch (err) {
      console.error(err);
    } finally {
      setDeleting(false);
    }
  };

  const getPriorityBadge = (p: string) => {
    if (p === "URGENT") {
      return (
        <Badge variant="destructive" className="animate-pulse flex items-center gap-1 text-[10px]">
          <AlertTriangle className="h-3 w-3" /> Genting / Penting Sekali
        </Badge>
      );
    }
    if (p === "IMPORTANT") {
      return <Badge variant="warning" className="text-[10px]">Penting</Badge>;
    }
    return <Badge variant="secondary" className="text-[10px]">Biasa</Badge>;
  };

  const getTargetBadge = (t: string) => {
    switch (t) {
      case "ALL":
        return <Badge variant="info" className="text-[10px]">Semua Warga Sekolah</Badge>;
      case "ALL_STUDENTS":
        return <Badge variant="outline" className="text-[10px] border-blue-300 text-blue-700">Seluruh Siswa</Badge>;
      case "ALL_TEACHERS":
        return <Badge variant="outline" className="text-[10px] border-purple-300 text-purple-700">Dewan Guru</Badge>;
      case "SPECIFIC_CLASS":
        return <Badge variant="outline" className="text-[10px] border-amber-300 text-amber-700">Kelas Khusus</Badge>;
      default:
        return null;
    }
  };

  return (
    <div className="space-y-4">
      {/* Controls */}
      <Card>
        <CardContent className="p-4 flex flex-col sm:flex-row items-center justify-between gap-3">
          <div className="flex items-center gap-2 w-full sm:w-auto flex-1">
            <div className="relative w-full sm:w-80">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
              <Input
                placeholder="Cari pengumuman..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-9 text-xs"
              />
            </div>
            <select
              value={priorityFilter}
              onChange={(e) => setPriorityFilter(e.target.value)}
              className="text-xs bg-white border border-slate-300 rounded-lg px-3 py-2 text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="ALL">Semua Prioritas</option>
              <option value="URGENT">Genting (Urgent)</option>
              <option value="IMPORTANT">Penting</option>
              <option value="NORMAL">Biasa</option>
            </select>
          </div>

          {canCreate && (
            <Button size="sm" onClick={handleOpenCreate} className="text-xs shrink-0 bg-blue-600 hover:bg-blue-700">
              <Plus className="h-3.5 w-3.5 mr-1" />
              Buat Pengumuman
            </Button>
          )}
        </CardContent>
      </Card>

      {/* Announcements Feed */}
      {loading ? (
        <div className="p-12 text-center text-slate-400 text-xs">Memuat pengumuman...</div>
      ) : announcements.length === 0 ? (
        <div className="p-12 text-center text-slate-500 bg-white rounded-xl border border-slate-200">
          <Bell className="h-10 w-10 text-slate-300 mx-auto mb-2" />
          <p className="font-semibold text-slate-700">Belum ada pengumuman</p>
          <p className="text-xs text-slate-400 mt-1">
            Pengumuman resmi dari sekolah atau dewan guru akan tampil di sini.
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {announcements.map((item) => {
            const authorName = item.author.teacher?.fullName || item.author.username;
            const canManage =
              currentUserRole === "ADMIN" || item.author.id === currentUserId;

            return (
              <Card
                key={item.id}
                className={`transition-all hover:border-slate-300 ${
                  item.priority === "URGENT"
                    ? "border-l-4 border-l-rose-500 bg-rose-50/10"
                    : item.priority === "IMPORTANT"
                    ? "border-l-4 border-l-amber-500"
                    : "border-l-4 border-l-blue-500"
                }`}
              >
                <CardContent className="p-5 space-y-3">
                  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-slate-100 pb-3">
                    <div className="flex flex-wrap items-center gap-2">
                      {getPriorityBadge(item.priority)}
                      {getTargetBadge(item.target)}
                      <span className="text-[11px] text-slate-400 font-medium">
                        {formatDateID(item.createdAt)}
                      </span>
                    </div>

                    {canManage && (
                      <div className="flex items-center gap-1">
                        <button
                          onClick={() => handleOpenEdit(item)}
                          className="p-1 text-slate-400 hover:text-blue-600 transition-colors rounded hover:bg-slate-100"
                          title="Edit Pengumuman"
                        >
                          <Edit2 className="h-3.5 w-3.5" />
                        </button>
                        <button
                          onClick={() => setDeleteTarget(item)}
                          className="p-1 text-slate-400 hover:text-rose-600 transition-colors rounded hover:bg-slate-100"
                          title="Hapus Pengumuman"
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    )}
                  </div>

                  <div>
                    <h3 className="text-base font-bold text-slate-900 leading-snug">
                      {item.title}
                    </h3>
                    <p className="text-xs text-slate-700 whitespace-pre-line leading-relaxed mt-2">
                      {item.content}
                    </p>
                  </div>

                  {/* Attachments */}
                  {item.attachments && item.attachments.length > 0 && (
                    <div className="pt-2 flex flex-wrap gap-2">
                      {item.attachments.map((att) => (
                        <a
                          key={att.id}
                          href={att.filePath}
                          target="_blank"
                          rel="noreferrer"
                          className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-blue-50 hover:text-blue-700 text-slate-700 text-xs font-medium transition-colors border border-slate-200"
                        >
                          <Paperclip className="h-3 w-3 text-slate-400" />
                          <span className="truncate max-w-[200px]">{att.fileName}</span>
                        </a>
                      ))}
                    </div>
                  )}

                  {/* Author footer */}
                  <div className="pt-2 flex items-center gap-2 text-[11px] text-slate-500">
                    <User className="h-3.5 w-3.5 text-slate-400" />
                    <span>Diterbitkan oleh: <strong className="text-slate-700">{authorName}</strong></span>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* Create / Edit Modal */}
      {modalOpen && (
        <Modal
          isOpen={true}
          onClose={() => setModalOpen(false)}
          title={editingId ? "Ubah Pengumuman" : "Buat Pengumuman Baru"}
        >
          <form onSubmit={handleSave} className="space-y-4 text-xs">
            {formError && (
              <div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 rounded-lg text-xs">
                {formError}
              </div>
            )}

            <div>
              <label className="block font-semibold text-slate-700 mb-1">
                Judul Pengumuman <span className="text-rose-500">*</span>
              </label>
              <Input
                placeholder="Contoh: Jadwal Pelaksanaan Ujian Tengah Semester Ganjil"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                required
                className="text-xs"
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Prioritas
                </label>
                <select
                  value={priority}
                  onChange={(e: any) => setPriority(e.target.value)}
                  className="w-full bg-white border border-slate-300 rounded-lg px-3 py-2 text-xs text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="NORMAL">Biasa (Normal)</option>
                  <option value="IMPORTANT">Penting (Important)</option>
                  <option value="URGENT">Genting (Urgent)</option>
                </select>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Target Sasaran
                </label>
                <select
                  value={target}
                  onChange={(e) => setTarget(e.target.value)}
                  className="w-full bg-white border border-slate-300 rounded-lg px-3 py-2 text-xs text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="ALL">Semua Warga Sekolah</option>
                  <option value="ALL_STUDENTS">Seluruh Siswa</option>
                  <option value="ALL_TEACHERS">Seluruh Dewan Guru</option>
                </select>
              </div>
            </div>

            <div>
              <label className="block font-semibold text-slate-700 mb-1">
                Isi Pengumuman <span className="text-rose-500">*</span>
              </label>
              <Textarea
                placeholder="Tuliskan instruksi atau pesan pengumuman selengkapnya di sini..."
                value={content}
                onChange={(e) => setContent(e.target.value)}
                rows={5}
                required
                className="text-xs"
              />
            </div>

            <div className="pt-2 flex justify-end gap-2">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => setModalOpen(false)}
              >
                Batal
              </Button>
              <Button
                type="submit"
                size="sm"
                disabled={submitting}
                className="bg-blue-600 hover:bg-blue-700"
              >
                {submitting ? "Menyimpan..." : editingId ? "Perbarui" : "Terbitkan Pengumuman"}
              </Button>
            </div>
          </form>
        </Modal>
      )}

      {/* Confirm Delete */}
      <ConfirmModal
        isOpen={!!deleteTarget}
        onClose={() => setDeleteTarget(null)}
        onConfirm={handleDelete}
        title="Hapus Pengumuman"
        message={`Apakah Anda yakin ingin menghapus pengumuman "${deleteTarget?.title}"? Tindakan ini tidak dapat dibatalkan.`}
        confirmLabel="Ya, Hapus"
        isDestructive={true}
        isLoading={deleting}
      />
    </div>
  );
}
