// src/app/(authenticated)/instagram-posts/page.tsx
"use client";

import React, { useState } from "react";
import { Edit2, PlayCircle, PauseCircle, Trash2 } from "react-feather";
// import { useRouter } from "next/navigation";
import InstagramPostsTable, { InstagramTableColumn } from "@/components/InstagramPostsTable";
import { InstagramPost } from "@/types";
import { logger } from "@/lib/logger";

export default function InstagramPostsPage() {
    // const router = useRouter();
    const [tableKey, setTableKey] = useState(0);

    const reloadTable = () => {
        logger.log("Reloading table");
        setTableKey((k) => k + 1);
    };

    // Define table columns for Instagram posts
    const columns: InstagramTableColumn[] = [
        {
            key: "media_url",
            label: "Post",
            render: (value, row) => {
                // Use thumbnail_url for VIDEO posts, otherwise use media_url
                const imageUrl = row.media_type === "VIDEO" && row.thumbnail_url 
                    ? row.thumbnail_url 
                    : String(value);
                const isVideo = row.media_type === "VIDEO";
                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' 
                            }}
                        />
                        {isVideo && (
                            <div className="video-indicator">
                                <PlayCircle size={16} />
                            </div>
                        )}
                    </a>
                );
            }
        },
        {
            key: "caption",
            label: "Caption",
            render: (value) => {
                const caption = String(value);
                return caption.length > 50 
                    ? `${caption.substring(0, 50)}...` 
                    : caption;
            }
        },
        {
            key: "created_at",
            label: "Created Date",
            sortable: true,
            render: (value) => {
                const dateStr = String(value);
                const formattedDate = new Date(dateStr).toLocaleDateString(
                    "en-US",
                    { month: "short", day: "numeric", year: "numeric" }
                );
                return formattedDate;
            }
        },
        {
            key: "comments_count",
            label: "Comments",
            sortable: true
        },
        {
            key: "like_count",
            label: "Likes",
            sortable: true
        },
        {
            key: "dm_count",
            label: "DMs Sent",
            sortable: true
        },
        {
            key: "media_type",
            label: "Type",
            render: (value) => {
                const type = String(value);
                return (
                    <span className={`badge ${type === 'VIDEO' ? 'badge-primary' : 'badge-secondary'}`}>
                        {type}
                    </span>
                );
            }
        },
        {
            key: "status",
            label: "Status",
            sortable: true,
            render: (value) => {
                const status = String(value);
                const statusClasses = {
                    'Completed': 'completed-text',
                    'Pending': 'pending-text',
                    'Active': 'active-text',
                    'Paused': 'paused-text',
                    'Failed': 'failed-text'
                } as const;

                return (
                    <span className={`mb-0 ${statusClasses[status as keyof typeof statusClasses] || 'pending-text'}`}>
                        {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 === 'Active' ? (
                        <button
                            className="no-bg-btn mx-2"
                            onClick={() => handleRowAction('pause', row)}
                            title="Pause"
                        >
                            <PauseCircle size={14} className="icon-btn-pause" />
                        </button>
                    ) : row.status === 'Paused' ? (
                        <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>
                </div>
            )
        }
    ];

    // Handle row actions
    const handleRowAction = (action: string, row: InstagramPost & { status: string }) => {
        switch (action) {
            case 'edit':
                // Navigate to edit page or open edit modal
                break;
            case 'pause':
                // API call to pause
                reloadTable();
                break;
            case 'resume':
                // API call to resume
                reloadTable();
                break;
            case 'delete':
                if (!window.confirm("Are you sure you want to delete this post?")) {
                    return;
                }
                // API call to delete
                reloadTable();
                break;
            default:
        }
    };

    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">
                    <div className="col-12">
                        <div className="page-header">
                            <div className="page-block">
                                <div className="row align-items-center">
                                    <div className="col-md-12">
                                        <div className="page-header-title">
                                            <h4 className="m-b-10">Instagram Posts</h4>
                                            <p className="m-b-0">
                                                Manage and monitor your Instagram posts performance
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <InstagramPostsTable
                        key={tableKey}
                        apiEndpoint="/api/instagram/posts"
                        columns={columns}
                        searchPlaceholder="Search posts by caption or type"
                        showDateFilter={true}
                        showSearch={true}
                        itemsPerPage={10}
                        tableId="instagramPostsTable"
                        onRowAction={handleRowAction}
                    />
                </div>
            </div>
        </div>
    );
}
