"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input, Textarea } from "@/components/ui/Field";
import { TeacherModal } from "@/components/teacher/ui/TeacherModal";
import { ApiError, apiGet, apiPost } from "@/lib/api";

interface ResourceItem {
  id: number;
  title?: string | null;
  original_name: string;
}

interface SocialPair {
  pair_id: number;
  title: string;
  channel_id?: number | null;
  group_id?: number | null;
}

interface SocialSpaceOption {
  id: number;
  label: string;
  type: "group" | "channel";
}

function buildResourceShareUrl(
  classRoomId: number,
  resourceId: number,
  subjectId?: number | null,
  scheduleId?: number | null,
) {
  const params = new URLSearchParams();
  params.set("tab", "resources");
  params.set("resource_id", String(resourceId));
  if (subjectId) params.set("subject_id", String(subjectId));
  if (scheduleId) params.set("schedule_id", String(scheduleId));
  return `${window.location.origin}/teacher/classes/${classRoomId}?${params.toString()}`;
}

export function ResourceShareModal({
  open,
  onClose,
  resource,
  classRoomId,
  subjectId,
  scheduleId,
}: {
  open: boolean;
  onClose: () => void;
  resource: ResourceItem | null;
  classRoomId: number;
  subjectId?: number | null;
  scheduleId?: number | null;
}) {
  const [spaces, setSpaces] = useState<SocialSpaceOption[]>([]);
  const [loadingSpaces, setLoadingSpaces] = useState(false);
  const [selectedSpaceId, setSelectedSpaceId] = useState<number | null>(null);
  const [message, setMessage] = useState("");
  const [sharing, setSharing] = useState(false);
  const [copied, setCopied] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const shareUrl = useMemo(() => {
    if (!resource || typeof window === "undefined") return "";
    return buildResourceShareUrl(classRoomId, resource.id, subjectId, scheduleId);
  }, [classRoomId, resource, scheduleId, subjectId]);

  const resourceLabel = resource?.title || resource?.original_name || "منبع";

  const loadSpaces = useCallback(async () => {
    if (!subjectId) {
      setSpaces([]);
      return;
    }
    setLoadingSpaces(true);
    setError(null);
    try {
      const pair = await apiGet<SocialPair>(
        `/social/pairs/resolve?class_room_id=${classRoomId}&subject_id=${subjectId}`,
      );
      const options: SocialSpaceOption[] = [];
      if (pair.group_id) {
        options.push({ id: pair.group_id, label: "گروه گفتگو", type: "group" });
      }
      if (pair.channel_id) {
        options.push({ id: pair.channel_id, label: "کانال کلاس", type: "channel" });
      }
      setSpaces(options);
      setSelectedSpaceId(options[0]?.id ?? null);
    } catch (err) {
      setSpaces([]);
      if (err instanceof ApiError && err.status !== 403) {
        setError(err.message);
      }
    } finally {
      setLoadingSpaces(false);
    }
  }, [classRoomId, subjectId]);

  useEffect(() => {
    if (!open) return;
    setCopied(false);
    setSuccess(null);
    setError(null);
    setMessage("");
    void loadSpaces();
  }, [loadSpaces, open]);

  const copyLink = async () => {
    if (!shareUrl) return;
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch {
      setError("کپی لینک ممکن نشد. لینک را دستی انتخاب کنید.");
    }
  };

  const shareToSocial = async () => {
    if (!resource || !selectedSpaceId || !shareUrl) return;
    setSharing(true);
    setError(null);
    setSuccess(null);
    try {
      const payload = await apiPost<{ post_id: number; space_id: number }>(
        `/teacher/resources/${resource.id}/share-to-social`,
        {
          space_id: selectedSpaceId,
          share_url: shareUrl,
          message: message.trim() || undefined,
        },
      );
      setSuccess("منبع در شبکه اجتماعی منتشر شد.");
      setMessage("");
      return payload;
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در اشتراک‌گذاری");
    } finally {
      setSharing(false);
    }
  };

  return (
    <TeacherModal
      open={open}
      onClose={onClose}
      title="ارسال به گروه"
      subtitle={resourceLabel}
      footer={
        <div className="flex flex-wrap gap-2">
          <Button variant="secondary" onClick={onClose}>
            بستن
          </Button>
          {spaces.length > 0 ? (
            <Button onClick={() => void shareToSocial()} loading={sharing} disabled={!selectedSpaceId}>
              ارسال به شبکه اجتماعی
            </Button>
          ) : null}
        </div>
      }
    >
      <div className="space-y-4">
        {error ? <Alert tone="error">{error}</Alert> : null}
        {success ? <Alert tone="success">{success}</Alert> : null}

        <Field label="لینک اشتراک‌گذاری">
          <div className="flex flex-wrap gap-2">
            <Input readOnly value={shareUrl} className="min-w-0 flex-1 font-mono text-xs" dir="ltr" />
            <Button variant="secondary" onClick={() => void copyLink()}>
              {copied ? "کپی شد ✓" : "کپی لینک"}
            </Button>
          </div>
          <p className="mt-1 text-xs text-slate-500">
            با این لینک، کاربران مجاز می‌توانند مستقیم به همین منبع در کلاس بروند.
          </p>
        </Field>

        {subjectId ? (
          <div className="space-y-3 rounded-xl border border-slate-200 bg-slate-50/80 p-3">
            <div>
              <h4 className="text-sm font-bold text-slate-800">اشتراک در شبکه اجتماعی</h4>
              <p className="mt-0.5 text-xs text-slate-500">
                منبع به‌صورت پیام با دکمه «مشاهده» در گروه یا کانال کلاس منتشر می‌شود.
              </p>
            </div>

            {loadingSpaces ? (
              <p className="text-xs text-slate-400">در حال بارگذاری گروه‌ها…</p>
            ) : spaces.length === 0 ? (
              <p className="text-xs text-slate-500">گروه شبکه اجتماعی برای این کلاس/درس یافت نشد.</p>
            ) : (
              <>
                <Field label="مقصد">
                  <div className="flex flex-wrap gap-2">
                    {spaces.map((space) => (
                      <button
                        key={space.id}
                        type="button"
                        onClick={() => setSelectedSpaceId(space.id)}
                        className={`rounded-lg px-3 py-1.5 text-sm font-medium transition ${
                          selectedSpaceId === space.id
                            ? "bg-teal-100 text-teal-800 ring-1 ring-teal-200"
                            : "bg-white text-slate-600 ring-1 ring-slate-200 hover:bg-slate-50"
                        }`}
                      >
                        {space.label}
                      </button>
                    ))}
                  </div>
                </Field>

                <Field label="پیام (اختیاری)">
                  <Textarea
                    rows={2}
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    placeholder={`📚 منبع آموزشی: ${resourceLabel}`}
                  />
                </Field>

                {success && selectedSpaceId ? (
                  <Link
                    href={`/social/${selectedSpaceId}`}
                    className="inline-flex text-sm font-medium text-teal-700 hover:underline"
                  >
                    مشاهده در شبکه اجتماعی ←
                  </Link>
                ) : null}
              </>
            )}
          </div>
        ) : (
          <Alert tone="info">برای اشتراک در شبکه اجتماعی، درس کلاس باید مشخص باشد.</Alert>
        )}
      </div>
    </TeacherModal>
  );
}

export { buildResourceShareUrl };
