import { createAdminClient } from "@/lib/supabase/admin";
import { AuthenticatedUser } from "@/types/auth";

export interface DashboardNotification {
  id: string;
  title: string;
  description: string;
  time: string;
  timestamp: string;
  type: "info" | "warning" | "success";
  unread: boolean;
  link?: string;
}

function formatRelativeTime(dateInput: string | Date): string {
  try {
    const d = typeof dateInput === "string" ? new Date(dateInput) : dateInput;
    const now = new Date();
    const diffMs = now.getTime() - d.getTime();
    const diffSecs = Math.floor(diffMs / 1000);
    const diffMins = Math.floor(diffSecs / 60);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffSecs < 60) return "Just now";
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHours < 24) return `${diffHours}h ago`;
    if (diffDays === 1) return "Yesterday";
    if (diffDays < 7) return `${diffDays}d ago`;
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  } catch {
    return "Recently";
  }
}

/**
 * Fetch dynamic real-time notifications for an authenticated dashboard user
 */
export async function getNotificationsForUser(
  actor: AuthenticatedUser | null
): Promise<DashboardNotification[]> {
  const notifications: DashboardNotification[] = [];
  const supabase = createAdminClient();

  if (!actor) {
    return [
      {
        id: "sys-welcome",
        title: "Welcome to Nigeria Listing",
        description: "Explore verified real estate opportunities across Nigeria's 36 states.",
        time: "Just now",
        timestamp: new Date().toISOString(),
        type: "info",
        unread: true,
        link: "/properties",
      },
    ];
  }

  const isStaff =
    actor.roles.includes("SUPER_ADMIN") ||
    actor.roles.includes("EMPLOYEE") ||
    actor.email.includes("admin") ||
    actor.email.includes("moderator") ||
    actor.email.includes("jega");

  // 1. Fetch Real Leads & Inquiries for this user
  try {
    const { data: leads } = await supabase
      .from("leads")
      .select(`
        id, client_name, full_name, client_email, email, message, inquiry_type,
        status, preferred_viewing_date, created_at,
        property:properties(id, title, slug)
      `)
      .or(`assigned_to_user_id.eq.${actor.id},user_id.eq.${actor.id}`)
      .order("created_at", { ascending: false })
      .limit(6);

    if (leads && leads.length > 0) {
      for (const lead of leads) {
        const client = lead.client_name || lead.full_name || "A client";
        const propTitle = (lead.property as any)?.title || "a property";
        const isViewing =
          lead.inquiry_type === "SCHEDULE_VIEWING" ||
          lead.status === "VIEWING_SCHEDULED";

        if (isViewing) {
          notifications.push({
            id: `lead-viewing-${lead.id}`,
            title: "Viewing Inspection Scheduled",
            description: `${client} requested a viewing for "${propTitle}".`,
            time: formatRelativeTime(lead.created_at),
            timestamp: lead.created_at,
            type: "info",
            unread: lead.status === "VIEWING_SCHEDULED" || lead.status === "NEW",
            link: "/dashboard/crm",
          });
        } else {
          notifications.push({
            id: `lead-inq-${lead.id}`,
            title: "New Client Inquiry",
            description: `${client} inquired: "${(lead.message || "").slice(0, 50)}${
              (lead.message || "").length > 50 ? "..." : ""
            }"`,
            time: formatRelativeTime(lead.created_at),
            timestamp: lead.created_at,
            type: "info",
            unread: lead.status === "NEW",
            link: "/dashboard/crm",
          });
        }
      }
    }
  } catch (err) {
    console.warn("[Notification Service Leads Fetch Warning]:", err);
  }

  // 2. Staff / Moderator Notifications (Pending Review Listings & Fraud Reports)
  if (isStaff) {
    try {
      // Pending review properties
      const { data: pendingProps } = await supabase
        .from("properties")
        .select("id, title, slug, created_at")
        .eq("status", "PENDING_REVIEW")
        .order("created_at", { ascending: false })
        .limit(3);

      if (pendingProps && pendingProps.length > 0) {
        for (const p of pendingProps) {
          notifications.push({
            id: `mod-prop-${p.id}`,
            title: "Listing Awaiting Moderation",
            description: `"${p.title}" was submitted and requires compliance check.`,
            time: formatRelativeTime(p.created_at),
            timestamp: p.created_at,
            type: "warning",
            unread: true,
            link: "/admin/properties?status=PENDING_REVIEW",
          });
        }
      }

      // Reported listing alerts from audit logs
      const { data: reports } = await supabase
        .from("audit_logs")
        .select("id, action, new_state, created_at")
        .eq("action", "PROPERTY_REPORTED")
        .order("created_at", { ascending: false })
        .limit(3);

      if (reports && reports.length > 0) {
        for (const rep of reports) {
          const state = (rep.new_state as any) || {};
          notifications.push({
            id: `rep-alert-${rep.id}`,
            title: "Listing Fraud Alert",
            description: `Flagged (${state.reason || "Suspicious"}): "${state.propertyTitle || "Property"}"`,
            time: formatRelativeTime(rep.created_at),
            timestamp: rep.created_at,
            type: "warning",
            unread: true,
            link: "/admin/audit-logs",
          });
        }
      }
    } catch (err) {
      console.warn("[Notification Service Moderation Warning]:", err);
    }
  }

  // 3. Publisher Notifications (Properties Approved/Published or Submitted)
  try {
    const { data: userProps } = await supabase
      .from("properties")
      .select("id, title, status, slug, updated_at, published_at")
      .eq("created_by_user_id", actor.id)
      .order("updated_at", { ascending: false })
      .limit(3);

    if (userProps && userProps.length > 0) {
      for (const p of userProps) {
        if (p.status === "PUBLISHED") {
          notifications.push({
            id: `prop-pub-${p.id}`,
            title: "Listing Live & Verified",
            description: `"${p.title}" is published and live for buyers on the marketplace.`,
            time: formatRelativeTime(p.published_at || p.updated_at),
            timestamp: p.published_at || p.updated_at,
            type: "success",
            unread: false,
            link: `/properties/${p.slug}`,
          });
        } else if (p.status === "PENDING_REVIEW") {
          notifications.push({
            id: `prop-rev-${p.id}`,
            title: "Listing Under Review",
            description: `"${p.title}" has been submitted for compliance approval.`,
            time: formatRelativeTime(p.updated_at),
            timestamp: p.updated_at,
            type: "info",
            unread: true,
            link: "/dashboard/properties",
          });
        }
      }
    }
  } catch (err) {
    console.warn("[Notification Service User Props Warning]:", err);
  }

  // 4. Agency CAC & Agent KYC Accreditation Notifications
  try {
    const [kycRes, agencyRes] = await Promise.all([
      supabase
        .from("agent_verifications")
        .select("id, status, action_required_reason, updated_at")
        .eq("user_id", actor.id)
        .order("created_at", { ascending: false })
        .limit(1)
        .maybeSingle(),
      supabase
        .from("agencies")
        .select("id, name, is_verified, is_active, updated_at, created_at")
        .or(`owner_id.eq.${actor.id},email.ilike.${actor.email.trim()}`)
        .order("created_at", { ascending: false })
        .limit(1)
        .maybeSingle(),
    ]);

    const kyc = kycRes.data;
    if (kyc) {
      if (kyc.status === "APPROVED" && !actor.roles.includes("AGENT")) {
        notifications.push({
          id: `kyc-appr-${kyc.id}`,
          title: "Agent KYC Accreditation Approved! 🎖️",
          description: "Your realtor credentials have been verified. Click to complete payment and activate your Verified Agent status.",
          time: formatRelativeTime(kyc.updated_at),
          timestamp: kyc.updated_at,
          type: "success",
          unread: true,
          link: "/dashboard/verification",
        });
      } else if (kyc.status === "NEEDS_ACTION") {
        notifications.push({
          id: `kyc-action-${kyc.id}`,
          title: "Action Required: KYC Verification",
          description: kyc.action_required_reason || "Please update your verification documents to proceed.",
          time: formatRelativeTime(kyc.updated_at),
          timestamp: kyc.updated_at,
          type: "warning",
          unread: true,
          link: "/dashboard/verification",
        });
      }
    }

    const agency = agencyRes.data;
    if (agency) {
      if (agency.is_verified && !agency.is_active) {
        notifications.push({
          id: `agency-appr-${agency.id}`,
          title: "Agency CAC Verification Approved! 🎉",
          description: `Corporate credentials for "${agency.name}" are approved. Click to complete payment and activate your Agency Workspace.`,
          time: formatRelativeTime(agency.updated_at),
          timestamp: agency.updated_at,
          type: "success",
          unread: true,
          link: "/dashboard/agency",
        });
      } else if (!agency.is_verified) {
        notifications.push({
          id: `agency-pending-${agency.id}`,
          title: "Agency Vetting Under Review",
          description: `Your CAC documents for "${agency.name}" are being reviewed by our compliance team.`,
          time: formatRelativeTime(agency.created_at),
          timestamp: agency.created_at,
          type: "info",
          unread: false,
          link: "/dashboard/agency",
        });
      }
    }
  } catch (err) {
    console.warn("[Notification Service KYC/Agency Warning]:", err);
  }

  // 5. Fallback / Starter Notifications if no activity yet
  if (notifications.length === 0) {
    notifications.push(
      {
        id: "sys-account-active",
        title: "Account Ready",
        description: "Your dashboard is connected and ready to receive client inquiries and viewing requests.",
        time: "Today",
        timestamp: new Date().toISOString(),
        type: "success",
        unread: false,
        link: "/dashboard",
      },
      {
        id: "sys-post-ad",
        title: "Publish a Property",
        description: "Post a verified property ad with title documentation to start generating leads.",
        time: "Today",
        timestamp: new Date().toISOString(),
        type: "info",
        unread: false,
        link: "/dashboard/properties/new",
      },
      {
        id: "sys-kyc",
        title: "Verification Badge",
        description: "Complete your agency registration to obtain the green Verified badge.",
        time: "1d ago",
        timestamp: new Date().toISOString(),
        type: "info",
        unread: false,
        link: "/dashboard/profile",
      }
    );
  }

  // Sort newest first
  notifications.sort((a, b) => {
    return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
  });

  return notifications;
}
