import toast from "react-hot-toast";
import { ColumnsType } from "antd/es/table";
import { useDebounce } from "@/hooks/useDebounce";
import React, { useEffect, useState } from "react";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import { Search, Send, FileText, Clock, Building, Trash2 } from "lucide-react";
import { Card, Table, Button, Input, Pagination, Select, Spin, Empty, Popconfirm, Tooltip } from "antd";

type ResourceType = "TEST" | "PYQ" | "MOCK_TEST";

interface IInstitution {
  id: string;
  institutionName: string;
}

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

const RESOURCE_TYPES: { key: ResourceType; label: string; icon: React.ReactNode }[] = [
  { key: "TEST", label: "Tests", icon: <FileText size={15} /> },
  { key: "PYQ", label: "PYQ", icon: <Clock size={15} /> },
  { key: "MOCK_TEST", label: "Mock Tests", icon: <FileText size={15} /> },
];

const SharedResources: React.FC = () => {
  const [fromInstitutionId, setFromInstitutionId] = useState<string | null>(null);
  const [toInstitutionId, setToInstitutionId] = useState<string | null>(null);
  const [activeType, setActiveType] = useState<ResourceType>("TEST");

  const [institutions, setInstitutions] = useState<IInstitution[]>([]);
  const [fetchingInstitutions, setFetchingInstitutions] = useState(false);

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const [pagination, setPagination] = useState(paginationInitial);
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 600);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [sharing, setSharing] = useState(false);
  const [sharedStatus, setSharedStatus] = useState<"ALL" | "SHARED" | "NOT_SHARED">("ALL");

  const [subjects, setSubjects] = useState<any[]>([]);
  const [selectedSubjectId, setSelectedSubjectId] = useState<string | undefined>(undefined);
  const [loadingSubjects, setLoadingSubjects] = useState(false);

  const [exams, setExams] = useState<any[]>([]);
  const [selectedExamId, setSelectedExamId] = useState<string | undefined>(undefined);
  const [loadingExams, setLoadingExams] = useState(false);

  const [selectedYear, setSelectedYear] = useState<string | undefined>(undefined);

  const [stats, setStats] = useState<{ totalCount: number; sharedCount: number; availableCount: number } | null>(null);

  useEffect(() => {
    if (!fromInstitutionId || activeType !== "TEST") {
      setSubjects([]);
      setSelectedSubjectId(undefined);
      return;
    }

    (async () => {
      setLoadingSubjects(true);
      try {
        const res = await API_Instance.get(API_Constants.subjects, {
          params: { institutionId: fromInstitutionId, limit: 1000 },
        });
        setSubjects(res.data.data || []);
      } catch (err) {
        console.error("Failed to load subjects for institution", err);
      } finally {
        setLoadingSubjects(false);
      }
    })();
  }, [fromInstitutionId, activeType]);

  useEffect(() => {
    if (!fromInstitutionId || (activeType !== "PYQ" && activeType !== "MOCK_TEST")) {
      setExams([]);
      setSelectedExamId(undefined);
      return;
    }

    (async () => {
      setLoadingExams(true);
      try {
        const res = await API_Instance.get(API_Constants.exams, {
          params: { institutionId: fromInstitutionId, limit: 1000 },
        });
        setExams(res.data.data || []);
      } catch (err) {
        console.error("Failed to load exams for institution", err);
      } finally {
        setLoadingExams(false);
      }
    })();
  }, [fromInstitutionId, activeType]);

  useEffect(() => {
    (async () => {
      setFetchingInstitutions(true);
      try {
        const res = await API_Instance.get(API_Constants.users, {
          params: { role: "Institution", limit: 1000 },
        });
        setInstitutions(res.data.data || []);
      } catch {
        toast.error("Failed to load institutions");
      } finally {
        setFetchingInstitutions(false);
      }
    })();
  }, []);

  useEffect(() => {
    if (!fromInstitutionId || !toInstitutionId) {
      setData([]);
      setPagination(paginationInitial);
      return;
    }
    fetchResources(pagination.page, pagination.limit);
  }, [fromInstitutionId, activeType, debouncedSearch, toInstitutionId, sharedStatus, selectedSubjectId, selectedExamId, selectedYear]);

  useEffect(() => {
    setSelectedRowKeys([]);
    setSearch("");
    setSelectedSubjectId(undefined);
    setSelectedExamId(undefined);
    setSelectedYear(undefined);
    setStats(null);
    setPagination(paginationInitial);
  }, [fromInstitutionId, activeType]);

  const fetchResources = async (page = 1, limit = 10) => {
    if (!fromInstitutionId || !toInstitutionId) return;
    setLoading(true);
    try {
      const params: any = {
        institutionId: fromInstitutionId,
        resourceType: activeType,
        search: debouncedSearch,
        page,
        limit,
        targetInstitutionId: toInstitutionId,
      };

      if (sharedStatus !== "ALL") {
        params.sharedStatus = sharedStatus;
      }

      if (activeType === "TEST" && selectedSubjectId) {
        params.subjectId = selectedSubjectId;
      } else if ((activeType === "PYQ" || activeType === "MOCK_TEST") && selectedExamId) {
        params.examId = selectedExamId;
      }
      
      if (activeType === "PYQ" && selectedYear) {
        params.year = selectedYear;
      }

      const res = await API_Instance.get(API_Constants.sharedResourceAvailable, { params });
      setData(res.data.data || []);
      setPagination(res.data.meta || paginationInitial);
      if (res.data.stats) {
        setStats(res.data.stats);
      } else {
        setStats(null);
      }
    } catch (e) {
      toast.error(getAxiosErrorMessage(e));
    } finally {
      setLoading(false);
    }
  };

  const removeSharedResource = async (record: any) => {
    if (!record?.sharedId) return;

    try {
      await API_Instance.post(`${API_Constants.sharedResource}/remove`, {
        resourceType: activeType,
        sharedId: record.sharedId,
      });
      toast.success("Removed shared copy successfully");
      fetchResources(pagination.page, pagination.limit);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    }
  };

  const handleShare = async () => {
    if (!fromInstitutionId) return toast.error("Select a source institution.");
    if (!toInstitutionId) return toast.error("Select a target institution.");
    if (selectedRowKeys.length === 0) return toast.error("Select at least one resource to share.");

    setSharing(true);
    try {
      const endpoint =
        activeType === "TEST" ? "/share/test" :
        activeType === "PYQ" ? "/share/pyq" :
        "/share/mock-test";
      const res = await API_Instance.post(`${API_Constants.sharedResource}${endpoint}`, {
        resourceIds: selectedRowKeys,
        sourceInstitutionId: fromInstitutionId,
        targetInstitutionIds: [toInstitutionId],
      });
      if (res.data.success) {
        toast.success(res.data.message || "Resources shared successfully!");
        setSelectedRowKeys([]);
        fetchResources(pagination.page, pagination.limit);
      } else {
        toast.error(res.data.message || "Something went wrong");
      }
    } catch (e) {
      toast.error(getAxiosErrorMessage(e));
    } finally {
      setSharing(false);
    }
  };

  const testColumns: ColumnsType<any> = [
    {
      title: "Title",
      dataIndex: "title",
      key: "title",
      width: "20%",
      render: (text) => (
        <div className="flex flex-col">
          <span className="font-semibold text-slate-700">{text || "Untitled"}</span>
        </div>
      ),
    },
    {
      title: "Subject",
      dataIndex: "subject",
      key: "subject",
      width: "20%",
      render: (s) =>
        s?.subjectName ? (
          <span className="text-[12px] px-3 py-1 rounded-full bg-purple-100 text-purple-800 border border-purple-300 font-semibold shadow-sm">
            {s.subjectName}
          </span>
        ) : (
          <span className="text-slate-400 text-xs">—</span>
        ),
    },
    {
      title: "Questions",
      dataIndex: "_count",
      key: "questions",
      width: "20%",
      render: (c) => (
        <span className="text-sm font-semibold text-slate-700">{c?.testQuestions ?? 0}</span>
      ),
    },
    {
      title: "Status",
      key: "status",
      width: "20%",
      render: (_v, record: any) => (
        <div className="flex items-center gap-2">
          {record.isShared ? (
            <span className="text-[12px] px-3 py-1 rounded-full bg-green-100 text-green-800 border border-green-300 font-semibold shadow-sm">Shared</span>
          ) : (
            <span className="text-[12px] px-3 py-1 rounded-full bg-slate-100 text-slate-700 border border-slate-300 font-medium">Not shared</span>
          )}
        </div>
      ),
    },
    {
      title: "Actions",
      key: "actions",
      align: "right",
      width: "20%",
      render: (_v, record: any) => (
        <Tooltip title={record.isShared && !record.isRemovable ? "Cannot remove because students have already taken this test" : ""}>
          <div className="inline-block">
            <Popconfirm
              title="Remove shared resource"
              description="Are you sure you want to remove?"
              onConfirm={() => removeSharedResource(record)}
              disabled={!record.isShared || !record.isRemovable}
              okText="Yes"
              cancelText="No"
            >
              <Button
                type="text"
                danger
                icon={<Trash2 size={13} />}
                className={`text-xs px-3 py-1 rounded-md font-medium transition-all shadow-sm ${record.isShared && record.isRemovable ? "bg-red-100 text-red-700 border border-red-300 hover:bg-red-200" : "bg-gray-100 text-gray-400 pointer-events-none"}`}
                disabled={!record.isShared || !record.isRemovable}
              >
                Remove
              </Button>
            </Popconfirm>
          </div>
        </Tooltip>
      ),
    },
  ];

  const pyqColumns: ColumnsType<any> = [
    {
      title: "Title (Year)",
      dataIndex: "title",
      key: "title",
      width: "20%",
      render: (text, record: any) => (
        <span className="font-semibold text-slate-700">
          {text || "Untitled"} {record.year ? `(${record.year})` : ""}
        </span>
      ),
    },
    {
      title: "Exam",
      dataIndex: "exam",
      key: "exam",
      width: "30%",
      render: (exam) => (
        exam?.examName ? (
          <span className="text-[12px] px-3 py-1 rounded-full bg-blue-100 text-blue-800 border border-blue-300 font-semibold shadow-sm">
            {exam.examName}
          </span>
        ) : (
          <span className="text-slate-400 text-xs">—</span>
        )
      ),
    },
    {
      title: "Questions",
      dataIndex: "_count",
      key: "questions",
      width: "20%",
      render: (c) => (
        <span className="text-sm font-semibold text-slate-700">{c?.questions ?? 0}</span>
      ),
    },
    {
      title: "Status",
      key: "status",
      width: "20%",
      render: (_v, record: any) => (
        <div className="flex items-center gap-2">
          {record.isShared ? (
            <span className="text-[12px] px-3 py-1 rounded-full bg-green-100 text-green-800 border border-green-300 font-semibold shadow-sm">Shared</span>
          ) : (
            <span className="text-[12px] px-3 py-1 rounded-full bg-slate-100 text-slate-700 border border-slate-300 font-medium">Not shared</span>
          )}
        </div>
      ),
    },
    {
      title: "Actions",
      key: "actions",
      align: "right",
      width: "20%",
      render: (_v, record: any) => (
        <Tooltip title={record.isShared && !record.isRemovable ? "Cannot remove because students have already taken this test" : ""}>
          <div className="inline-block">
            <Popconfirm
              title="Remove shared resource"
              description="Are you sure you want to remove?"
              onConfirm={() => removeSharedResource(record)}
              disabled={!record.isShared || !record.isRemovable}
              okText="Yes"
              cancelText="No"
            >
              <Button
                type="text"
                danger
                icon={<Trash2 size={13} />}
                className={`text-xs px-3 py-1 rounded-md font-medium transition-all shadow-sm ${record.isShared && record.isRemovable ? "bg-red-100 text-red-700 border border-red-300 hover:bg-red-200" : "bg-gray-100 text-gray-400 pointer-events-none"}`}
                disabled={!record.isShared || !record.isRemovable}
              >
                Remove
              </Button>
            </Popconfirm>
          </div>
        </Tooltip>
      ),
    },
  ];

  const mockTestColumns: ColumnsType<any> = [
    {
      title: "Title",
      dataIndex: "title",
      key: "title",
      width: "20%",
      render: (text) => (
        <span className="font-semibold text-slate-700">{text || "Untitled"}</span>
      ),
    },
    {
      title: "Exam",
      dataIndex: "exam",
      key: "exam",
      width: "25%",
      render: (exam) =>
        exam?.examName ? (
          <span className="text-[12px] px-3 py-1 rounded-full bg-orange-100 text-orange-800 border border-orange-300 font-semibold shadow-sm">
            {exam.examName}
          </span>
        ) : (
          <span className="text-slate-400 text-xs">—</span>
        ),
    },
    {
      title: "Questions",
      dataIndex: "questionCount",
      key: "questionCount",
      width: "15%",
      render: (c) => (
        <span className="text-sm font-semibold text-slate-700">{c ?? 0}</span>
      ),
    },
    {
      title: "Status",
      key: "status",
      width: "20%",
      render: (_v, record: any) => (
        <div className="flex items-center gap-2">
          {record.isShared ? (
            <span className="text-[12px] px-3 py-1 rounded-full bg-green-100 text-green-800 border border-green-300 font-semibold shadow-sm">Shared</span>
          ) : (
            <span className="text-[12px] px-3 py-1 rounded-full bg-slate-100 text-slate-700 border border-slate-300 font-medium">Not shared</span>
          )}
        </div>
      ),
    },
    {
      title: "Actions",
      key: "actions",
      align: "right",
      width: "20%",
      render: (_v, record: any) => (
        <Tooltip title={record.isShared && !record.isRemovable ? "Cannot remove because students have taken this mock test" : ""}>
          <div className="inline-block">
            <Popconfirm
              title="Remove shared resource"
              description="Are you sure you want to remove?"
              onConfirm={() => removeSharedResource(record)}
              disabled={!record.isShared || !record.isRemovable}
              okText="Yes"
              cancelText="No"
            >
              <Button
                type="text"
                danger
                icon={<Trash2 size={13} />}
                className={`text-xs px-3 py-1 rounded-md font-medium transition-all shadow-sm ${record.isShared && record.isRemovable ? "bg-red-100 text-red-700 border border-red-300 hover:bg-red-200" : "bg-gray-100 text-gray-400 pointer-events-none"}`}
                disabled={!record.isShared || !record.isRemovable}
              >
                Remove
              </Button>
            </Popconfirm>
          </div>
        </Tooltip>
      ),
    },
  ];

  const getColumns = () => {
    if (activeType === "TEST") return testColumns;
    if (activeType === "MOCK_TEST") return mockTestColumns;
    return pyqColumns;
  };

  const institutionOptions = institutions.map((i) => ({
    label: i.institutionName,
    value: i.id,
  }));

  return (
    <div className="flex flex-col gap-4 px-4 py-6">
      {/* Page Header */}
      <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">
            <Send className="text-blue-600" /> Share Resources
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            Distribute Tests, PYQs, and Mock Tests across institutions.
          </p>
        </div>
      </div>

      {/* Setup Card */}
      <Card className="shadow-sm border border-slate-200 rounded-xl">
        <div className="flex flex-col gap-5">
          {/* Institution Selectors */}
          <div className="grid grid-cols-3 gap-4">
            <div className="flex flex-col gap-1.5">
              <label className="text-sm font-semibold text-slate-600 flex items-center gap-1.5">
                <Building size={14} className="text-slate-400" />
                From Institution
              </label>
              <Select
                showSearch
                allowClear
                className="w-full"
                placeholder="Select source institution"
                loading={fetchingInstitutions}
                options={institutionOptions}
                value={fromInstitutionId}
                onChange={(val) => {
                  setFromInstitutionId(val ?? null);
                  if (!val || val === toInstitutionId) {
                    setToInstitutionId(null);
                  }
                }}
                filterOption={(input, option) =>
                  (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
                }
              />
            </div>

            <div className="flex flex-col gap-1.5">
              <label className="text-sm font-semibold text-slate-600 flex items-center gap-1.5">
                <Building size={14} className="text-slate-400" />
                To Institution
              </label>
              <Select
                disabled={!fromInstitutionId}
                allowClear
                showSearch
                className="w-full"
                placeholder="Select target institution"
                loading={fetchingInstitutions}
                options={institutionOptions.filter((o) => o.value !== fromInstitutionId)}
                value={toInstitutionId}
                onChange={(val) => setToInstitutionId(val ?? null)}
                filterOption={(input, option) =>
                  (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
                }
              />
            </div>

            {/* Resource Type Selector */}
            <div className="flex flex-col gap-1.5">
              <label className="text-sm font-semibold text-slate-600">Resource Type</label>
              <Select
                value={activeType}
                onChange={(val) => setActiveType(val as ResourceType)}
                className="w-full"
                options={RESOURCE_TYPES.map(({ key, label }) => ({
                  label,
                  value: key,
                }))}
              />
            </div>
          </div>
        </div>
      </Card>

      {/* Resource List Card */}
      <Card className="shadow-sm border border-slate-200 rounded-xl">
        {fromInstitutionId && toInstitutionId && stats && (
          <div className="grid grid-cols-3 gap-4 mb-5">
            <Card size="small" className="bg-[#f8fafc] border-slate-100 rounded-xl shadow-sm text-center">
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">
                Total {activeType === "TEST" ? "Tests" : "PYQs"}
              </p>
              <p className="text-2xl font-bold text-slate-800">{stats.totalCount}</p>
            </Card>
            <Card size="small" className="bg-[#f8fafc] border-slate-100 rounded-xl shadow-sm text-center">
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">
                Shared {activeType === "TEST" ? "Tests" : "PYQs"}
              </p>
              <p className="text-2xl font-bold text-green-600">{stats.sharedCount}</p>
            </Card>
            <Card size="small" className="bg-[#f8fafc] border-slate-100 rounded-xl shadow-sm text-center">
              <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">
                Available {activeType === "TEST" ? "Tests" : "PYQs"}
              </p>
              <p className="text-2xl font-bold text-blue-600">{stats.availableCount}</p>
            </Card>
          </div>
        )}

        {/* Filter bar */}
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-4">
          <div className="flex flex-wrap items-center gap-3 w-full sm:w-auto">
            <div className="w-full md:w-72">
              <Input
                placeholder="Search by title..."
                prefix={<Search size={16} className="text-slate-400" />}
                allowClear
                value={search}
                disabled={!fromInstitutionId}
                onChange={(e) => setSearch(e.target.value)}
              />
            </div>

            {activeType === "TEST" && fromInstitutionId && (
              <div className="w-full md:w-56">
                <Select
                  placeholder="Filter by Subject"
                  className="w-full"
                  allowClear
                  loading={loadingSubjects}
                  value={selectedSubjectId}
                  onChange={(val) => setSelectedSubjectId(val)}
                  options={subjects.map((sub) => ({
                    label: sub.subjectName,
                    value: sub.id,
                  }))}
                />
              </div>
            )}

            {(activeType === "PYQ" || activeType === "MOCK_TEST") && fromInstitutionId && (
              <div className="w-full md:w-56">
                <Select
                  placeholder={activeType === "MOCK_TEST" ? "Filter by Exam" : "Filter by Exam"}
                  className="w-full"
                  allowClear
                  loading={loadingExams}
                  value={selectedExamId}
                  onChange={(val) => setSelectedExamId(val)}
                  options={exams.map((ex) => ({
                    label: ex.examName,
                    value: ex.id,
                  }))}
                />
              </div>
            )}

            {activeType === "PYQ" && fromInstitutionId && (
              <div className="w-full md:w-40">
                <Select
                  placeholder="Filter by Year"
                  className="w-full"
                  allowClear
                  value={selectedYear}
                  onChange={(val) => setSelectedYear(val)}
                  options={Array.from({ length: 30 }, (_, i) => {
                    const year = new Date().getFullYear() - i;
                    return { label: String(year), value: String(year) };
                  })}
                />
              </div>
            )}

            {fromInstitutionId && toInstitutionId && (
              <div className="w-full md:w-48">
                <Select
                  value={sharedStatus}
                  onChange={(val) => setSharedStatus(val as any)}
                  className="w-full"
                  options={[
                    { label: "All Resources", value: "ALL" },
                    { label: "Shared Resources", value: "SHARED" },
                    { label: "Available Resources", value: "NOT_SHARED" },
                  ]}
                />
              </div>
            )}
          </div>

          <div className="text-slate-500 text-sm whitespace-nowrap self-end sm:self-center">
            {selectedRowKeys.length > 0 && (
              <span className="font-semibold text-blue-600 mr-2">
                {selectedRowKeys.length} selected ·
              </span>
            )}
            Total:{" "}
            <span className="font-semibold text-slate-800">{pagination.total}</span>
          </div>
        </div>

        <Spin spinning={loading}>
          {!fromInstitutionId || !toInstitutionId ? (
            <div className="min-h-[200px] flex items-center justify-center">
              <Empty
                description={
                  <span className="text-slate-400">
                    Select a "From Institution" and a "To Institution" to preview resources
                  </span>
                }
              />
            </div>
          ) : data.length === 0 && !loading ? (
            <div className="min-h-[200px] flex items-center justify-center">
              <Empty
                description={
                  debouncedSearch
                    ? "No resources found matching your search"
                    : "No resources available for this institution"
                }
              />
            </div>
          ) : (
            <>
              <Table
                rowSelection={{
                  selectedRowKeys,
                  onChange: (keys) => setSelectedRowKeys(keys),
                  getCheckboxProps: (record) => ({
                    disabled: record.isShared,
                  }),
                }}
                columns={getColumns()}
                dataSource={data}
                rowKey="id"
                pagination={false}
                scroll={{ x: 700 }}
                className="border border-slate-100 rounded-lg overflow-hidden"
              />

              <div className="flex justify-end pt-4">
                <Pagination
                  current={pagination.page}
                  total={pagination.total}
                  pageSize={pagination.limit}
                  onChange={(page, pageSize) => {
                    setPagination((p) => ({ ...p, page, limit: pageSize }));
                    fetchResources(page, pageSize);
                  }}
                  showSizeChanger
                  showTotal={(total) => `Total ${total} items`}
                />
              </div>
            </>
          )}
        </Spin>

        {/* Share Button — shown once from-institution is selected */}
        {fromInstitutionId && (
          <div className="flex justify-end pt-4 border-t border-slate-100 mt-4">
            <Popconfirm
              title={`Share ${activeType.replace("_", " ")}`}
              description={`Are you sure you want to share?`}
              onConfirm={handleShare}
              disabled={selectedRowKeys.length === 0 || !toInstitutionId}
              okText="Yes"
              cancelText="No"
            >
              <Button
                type="primary"
                icon={<Send size={16} />}
                size="large"
                className="px-8"
                loading={sharing}
                disabled={selectedRowKeys.length === 0 || !toInstitutionId}
              >
                Share Selected
              </Button>
            </Popconfirm>
          </div>
        )}
      </Card>
    </div>
  );
};

export default SharedResources;