// src/app/auto-dm/history/page.tsx
"use client";

import React, { useState } from "react";
import { Edit2, PlayCircle, PauseCircle, Trash2, X } from "react-feather";
import { useRouter } from "next/navigation";
import { useAppDispatch, useAppSelector } from "@/hooks/useAppDispatch";
import {
  setPostToUpdate,
  setSelectedPost,
  setInstagramConnection
} from "@/features/autoDm/autoDmSlice";
import {
  updateAutoDmStatus,
  deleteAutoDmConfig,
  fetchPostDetails,
} from "@/features/autoDm/autoDmThunk";
import { useToast } from "@/components/ui/ToastContext";
import apiClient from "@/lib/apiClient";
import AutoDmHeader from "@/components/AutoDmHeader";
import DataTable, { TableColumn } from "@/components/DataTable";
// Alternative: Use InstagramPostsTable for Instagram posts with new API structure
// import InstagramPostsTable, { InstagramTableColumn } from "@/components/InstagramPostsTable";
import { logger } from "@/lib/logger";

interface PostData {
  id: string;
  media_url: string;
  media_type: "IMAGE" | "VIDEO";
  thumbnail_url?: string;
  lastModifiedDate: string;
  comments: number;
  dmsSent: number;
  status: "completed" | "pending" | "active" | "pause" | "start";
  paused_links?: boolean; // Optional field for paused links state
  [key: string]: unknown;
}

// Format date as YYYY-MM-DD
// const formatDate = (date: Date) => {
//   const year = date.getFullYear();
//   const month = String(date.getMonth() + 1).padStart(2, "0");
//   const day = String(date.getDate()).padStart(2, "0");
//   return `${year}-${month}-${day}`;
// };

// Calculate default last 7 days range
const today = new Date();
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(today.getDate() - 6);

export default function AutoDmHistory() {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const showToast = useToast();
  const [tableKey, setTableKey] = useState(0);

  // State for disconnect confirmation modal
  const [showDisconnectConfirmation, setShowDisconnectConfirmation] =
    useState(false);
  const [isDisconnecting, setIsDisconnecting] = useState(false);

  // Get username, connected from Redux store
  const { username, connected } = useAppSelector((state) => state.autoDm);

  const [isInitialLoad, setIsInitialLoad] = useState(true);

  const reloadTable = () => {
    setTableKey((k) => k + 1);
  };

  // disconnect instagram
  const disconnectInstagram = () => {
    setShowDisconnectConfirmation(true);
  };

  // Handle actual Instagram disconnection
  const handleDisconnectInstagram = async () => {
    try {
      setIsDisconnecting(true);
      const response = await apiClient.get("/ig/disconnect");

      if (response.data.success) {
        showToast("Your Instagram account has been disconnected.");
        dispatch(setInstagramConnection({ username: null, connected: false }));
        setShowDisconnectConfirmation(false);
        // Redirect to connect Instagram page
        router.push("/auto-dm/step-1");
      } else {
        showToast("Unable to disconnect right now. Please try again.");
      }
    } catch (error) {
      logger.error("Failed to disconnect Instagram:", error);
      showToast("Unable to disconnect right now. Please try again.");
    } finally {
      setIsDisconnecting(false);
    }
  };

  // Close disconnect confirmation modal
  const closeDisconnectConfirmation = () => {
    setShowDisconnectConfirmation(false);
  };

  // Define table columns
  const columns: TableColumn<PostData>[] = [
    {
      key: "media_url",
      label: "Post",
      render: (value, row) => {
        // Use thumbnail_url for VIDEO posts, otherwise use media_url
        const imageUrl =
          connected === false ? "/img/default-insta-post.png" :
            row.media_type === "VIDEO" && row.thumbnail_url
              ? row.thumbnail_url
              : String(value);

        return (
          <a href="#" className="d-block ig-post-img mx-auto my-0">
            <img
              src={imageUrl}
              alt="Instagram post"
              className="my-0 mx-auto"
              style={{
                width: "60px",
                height: "60px",
                objectFit: "cover",
                borderRadius: "8px",
              }}
            />
          </a>
        );
      },
    },
    {
      key: "updated_at",
      label: "Last Modified Date",
      sortable: true,
      render: (value) => {
        // Narrow unknown → string
        const dateStr = typeof value === "string" ? value : String(value);
        const formattedDate = new Date(dateStr).toLocaleDateString("en-US", {
          month: "short",
          day: "numeric",
          year: "numeric",
        });
        return formattedDate;
      },
    },
    {
      key: "comments_count",
      label: "Comments",
      sortable: false,
    },
    {
      key: "dm_count",
      label: "DMs Sent",
      sortable: false,
    },
    {
      key: "status",
      label: "Status",
      sortable: true,
      render: (value) => {
        const status = typeof value === "string" ? value : String(value);
        const statusClasses = {
          Completed: "completed-text",
          Pending: "pending-text",
          Active: "active-text",
          Paused: "paused-text",
        } as const;

        return (
         <span
  className={`mb-0 ${
    status === "start"
      ? "text-success" 
      : statusClasses[status as keyof typeof statusClasses] || "pending-text"
  }`}
>
  {status === "start"
    ? "Active"
    : status === "pause"
    ? "Paused"
    : status}
</span>

        );
      },
    },
    {
      key: "actions",
      label: "Actions",
      render: (_, row) => (
        <div className="d-flex justify-content-center align-items-center">
          <button
            className="no-bg-btn mx-2"
            onClick={() => handleRowAction("edit", row)}
            title="Edit"
          >
            <Edit2 size={14} className="icon-btn-edit" />
          </button>

          {row.status == "start" ? (
            <button
              className="no-bg-btn mx-2"
              onClick={() => handleRowAction("pause", row)}
              title="Pause"
            >
              <PauseCircle size={14} className="icon-btn-pause" />
            </button>
          ) : row.status == "pause" ? (
            <button
              className="no-bg-btn mx-2"
              onClick={() => handleRowAction("resume", row)}
              title="Resume"
            >
              <PlayCircle size={14} className="icon-btn-resume" />
            </button>
          ) : null}

          <button
            className="no-bg-btn mx-2"
            onClick={() => handleRowAction("delete", row)}
            title="Delete"
          >
            <Trash2 size={14} className="icon-btn-trash" />
          </button>

          {/* Paused links warning icon - always last */}
          {row.paused_links === true && (
            <button
              type="button"
              className="no-bg-btn mx-2 fw-medium paused-tooltip"
              data-bs-toggle="tooltip"
              data-bs-placement="top"
              data-bs-title="Links in your Auto-DM post are paused. Update your post now."
              title="Links in your Auto-DM post are paused. Update your post now."
            >
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M4 16H15.5L10 5L4 16Z" fill="white"/>
                <path d="M10.8333 11.6667H9.16668V7.50002H10.8333M10.8333 15H9.16668V13.3334H10.8333M0.833344 17.5H19.1667L10 1.66669L0.833344 17.5Z" fill="#FF7D09"/>
              </svg>
            </button>
          )}
        </div>
      ),
    },
  ];

  // Handle row actions
  const handleRowAction = async (action: string, row: PostData) => {
    switch (action) {
      case "edit":
        try {
          // 1. Fetch post details from API
          const igPostId = (row as { ig_post_id?: string }).ig_post_id || row.id; // fallback to id if ig_post_id is not available
          await dispatch(fetchPostDetails(String(igPostId))).unwrap();

          // 2. Store the ig_post_id for step-2
          dispatch(setPostToUpdate(igPostId));

          // 3. Also prime the selectedPost with metadata:
          dispatch(
            setSelectedPost({
              id: row.id,
              media_type: row.media_type,
              media_url: row.media_url,
            })
          );

          // 4. Navigate to step-2
          router.push("/auto-dm/step-2");
        } catch (error) {
          logger.error("Failed to load post details:", error);
          showToast("Failed to load post details. Please try again.");
        }
        break;
      case "pause":
        dispatch(
          updateAutoDmStatus({
            id: row.id,
            isActive: false,
            ig_post_id: String(row.ig_post_id),
          })
        )
          .unwrap()
          .then(() => {
            reloadTable();
          })
          .catch((e) => logger.error("Error pausing Auto-DM:", e));
        break;
      case "resume":
        dispatch(
          updateAutoDmStatus({
            id: row.id,
            isActive: true,
            ig_post_id: String(row.ig_post_id),
          })
        )
          .unwrap()
          .then(() => {
            reloadTable();
          })
          .catch((e) => logger.error("Error resuming Auto-DM:", e));
        break;
      case "delete":
        if (!window.confirm("Are you sure you want to delete this post?")) {
          return;
        }
        dispatch(deleteAutoDmConfig({ id: String(row.ig_post_id) }))
          .unwrap()
          .then(() => {
            reloadTable();
          })
          .catch((e) => {
            logger.error("Error deleting Auto-DM:", e);
          });
        break;
      default:
        logger.error("Invalid action:", action);
    }
  };

  const handleDataLoad = () => {
    // Only mark initial load complete once
    if (isInitialLoad) setIsInitialLoad(false);
  };

  return (
    <div className="pcoded-main-container bg-light webContent">
      <div className="pcoded-content">
        <div className="row align-items-center align-items-md-end mb-md-0 mb-2">
          <AutoDmHeader
            currentStep={0}
            totalSteps={0}
            username={username || ""}
            connected={connected}
            onDisconnect={disconnectInstagram}
            showNextButton={false}
          />
          <DataTable<PostData>
            key={tableKey}
            apiEndpoint="/ig/posts/partner-posts"
            columns={columns}
            searchPlaceholder="Search by keywords"
            showDateFilter={true}
            showSearch={true}
            itemsPerPage={10}
            tableId="autoDmHistoryTable"
            onRowAction={handleRowAction}
            reloadToken={tableKey}
            onDataLoad={handleDataLoad}
          />
        </div>

        {/* Disconnect Instagram Confirmation Modal */}
        {showDisconnectConfirmation && (
          <>
            {/* Backdrop */}
            <div
              className="modal-backdrop fade show"
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                width: "100vw",
                height: "100vh",
                backgroundColor: "rgba(0, 0, 0, 0.5)",
                zIndex: 1040,
                cursor: isDisconnecting ? "not-allowed" : "pointer",
              }}
              onClick={() => { if (!isDisconnecting) closeDisconnectConfirmation(); }}
              title="Click outside to close"
            />

            {/* Modal */}
            <section
              className="modal fade my-modal show d-block"
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                width: "100vw",
                height: "100vh",
                zIndex: 1050,
              }}
              aria-hidden="false"
              onClick={() => { if (!isDisconnecting) closeDisconnectConfirmation() }}
            >
              <div
                className="modal-dialog modal-dialog-centered"
                onClick={(e) => e.stopPropagation()}
              >
                <div
                  className="modal-content"
                  onClick={(e) => e.stopPropagation()}
                >
                  <div className="modal-body text-center p-3">
                    <div className="modal-name mb-0 d-flex justify-content-end">
                      <button
                        type="button"
                        className="btn-close"
                        onClick={closeDisconnectConfirmation}
                        aria-label="Close"
                        disabled={isDisconnecting}
                      >
                        <X size={20} />
                      </button>
                    </div>

                    <h4 className="mb-3">Disconnect Instagram?</h4>
                    <p className="px-2 mb-4">
                      This will stop Auto-DM functionality until you reconnect.
                    </p>

                    <div className="d-flex gap-2 justify-content-center">
                      <button
                        type="button"
                        className="btn btn-secondary"
                        onClick={closeDisconnectConfirmation}
                        disabled={isDisconnecting}
                      >
                        Cancel
                      </button>
                      <button
                        type="button"
                        className="btn btn-danger"
                        onClick={handleDisconnectInstagram}
                        disabled={isDisconnecting}
                      >
                        {isDisconnecting ? "Disconnecting..." : "Disconnect"}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </section>
          </>
        )}
      </div>
    </div>
  );
}
