import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import React, { useEffect, useState } from "react";
import { Card, Input, Spin, Pagination, Tag } from "antd";
import { Search, Link as LinkIcon, Database, BookOpen, FileText, Globe, ChevronRight } from "lucide-react";

import { useDebounce } from "@/hooks/useDebounce";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { getAxiosErrorMessage } from "@/utils/index.utils";

const paginationInitial = {
  page: 1,
  limit: 10,
  total: 0,
  totalPages: 0,
};

const NotesAndLinksPage: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 600);
  const [subjects, setSubjects] = useState<any[]>([]);
  const [pagination, setPagination] = useState(paginationInitial);

  const fetchSubjects = async (page = 1, limit = 10) => {
    setLoading(true);
    try {
      const res = await API_Instance.get(
        `${API_Constants.subjects}?page=${page}&limit=${limit}&search=${debouncedSearch}`
      );
      setSubjects(res.data.data);
      setPagination(res.data.meta || paginationInitial);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSubjects(1, pagination.limit);
  }, [debouncedSearch]);

  const handleSubjectClick = (subjectId: string) => {
    navigate(`${ROUTE_CONSTANTS.NotesAndLinksSubject}`.replace(':subjectId', subjectId));
  };

  return (
    <div className="flex flex-col gap-4 px-4 py-6">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
            <LinkIcon className="text-blue-600" size={24} /> Notes & Links
          </h2>
          <p className="text-slate-500 max-w-2xl">
            Select a subject to view resources, upload materials, and manage publishing to exams.
          </p>
        </div>
      </div>

      <Card className="shadow-sm border border-slate-200 rounded-xl">
        <div className="flex justify-between items-center mb-6">
          <div className="w-full md:w-80">
            <Input
              placeholder="Search subject by name..."
              prefix={<Search size={16} className="text-slate-400" />}
              allowClear
              size="large"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="rounded-lg"
            />
          </div>
        </div>

        <Spin spinning={loading}>
          {subjects.length === 0 && !loading ? (
            <div className="min-h-[300px] flex flex-col items-center justify-center text-slate-400 border-2 border-dashed border-slate-100 rounded-xl">
              <div className="bg-slate-50 p-4 rounded-full mb-4">
                <Database size={32} className="text-slate-300" />
              </div>
              <p className="font-medium text-slate-500">
                {search
                  ? "No subjects found matching your search"
                  : "No subjects available"}
              </p>
            </div>
          ) : (
            <div className="space-y-3 min-h-[200px]">
              {subjects.map((subj: any) => {
                const pdfCount = subj._count?.notesLinksPdf || subj.pdfCount || 0;
                const linkCount = subj._count?.notesLinksUrl || subj.linkCount || 0;
                
                const assignedExams = subj.exams || subj.assignedExams || [];

                return (
                  <div
                    key={subj.id}
                    onClick={() => handleSubjectClick(subj.id)}
                    className="group flex flex-col sm:flex-row sm:items-center justify-between p-4 bg-white hover:bg-blue-50/40 border border-slate-200 hover:border-blue-300 rounded-xl cursor-pointer transition-all duration-200 shadow-sm hover:shadow gap-4"
                  >
                    <div className="flex items-start gap-3 flex-1">
                      <div className="p-3 bg-blue-50 text-blue-600 rounded-lg group-hover:bg-blue-600 group-hover:text-white transition-colors duration-200 mt-0.5">
                        <BookOpen size={20} />
                      </div>

                      <div className="flex flex-col gap-1.5 flex-1">
                        <h3 className="text-base font-semibold text-slate-800 group-hover:text-blue-600 transition-colors">
                          {subj.subjectName}
                        </h3>

                        <div className="flex items-center gap-1.5 flex-wrap">
                          <span className="text-xs text-slate-400 font-medium flex items-center gap-1 mr-1">
                            Published To:
                          </span>

                          {assignedExams.length > 0 ? (
                            assignedExams.map((exam: any, idx: number) => (
                              <Tag
                                key={exam.id || idx}
                                className="px-2 py-0.5 text-xs rounded-md bg-amber-50 text-amber-800 border-amber-200 font-medium m-0"
                              >
                                {exam.title || exam.name || exam.examName}
                              </Tag>
                            ))
                          ) : (
                            <span className="text-xs text-slate-400 italic">
                              Not published to any exam yet
                            </span>
                          )}
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-4 justify-between sm:justify-end border-t sm:border-t-0 pt-3 sm:pt-0 border-slate-100">
                      <div className="flex items-center gap-4">
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                          }}
                          className="flex items-center gap-1.5 text-sm font-medium text-red-600 hover:text-red-700 transition-colors"
                        >
                          <FileText size={15} />
                          <span>{pdfCount} Notes</span>
                        </button>

                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                          }}
                          className="flex items-center gap-1.5 text-sm font-medium text-blue-600 hover:text-blue-700 transition-colors"
                        >
                          <Globe size={15} />
                          <span>{linkCount} Links</span>
                        </button>
                      </div>

                      <ChevronRight
                        size={18}
                        className="text-slate-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all"
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </Spin>

        <div className="flex justify-end mt-6">
          <Pagination
            current={pagination.page}
            total={pagination.total}
            pageSize={pagination.limit}
            onChange={(p, pageSize) => {
              fetchSubjects(p, pageSize);
            }}
            showSizeChanger
            showTotal={(total) => `Total ${total} subjects`}
          />
        </div>
      </Card>
    </div>
  );
};

export default NotesAndLinksPage;