"use client"

import { useState, useEffect } from "react"
import { UserCircle, Users, Eye, Settings, Trash2, Plus, Link, User, Crown, Shield } from "lucide-react"
import AppLayout from "@/Layouts/AppLayout"
import { Button } from "@/Components/UI/Button"
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"
import DataTable from "@/Components/DataTable"
import DeleteModal from "@/Components/DeleteModal"
import PlatformIcon from "@/Components/UI/PlatformIcon"
import ConnectAccountModal from "@/Components/Post/ConnectAccountModal"
import { useDeleteHandler } from "@/hooks/useDeleteHandler"
import { useToggleHandler } from "@/hooks/useToggleHandler"
import { useBulkHandler } from "@/hooks/useBulkHandler"
import useTranslate from "@/hooks/useTranslate"
import { router } from "@inertiajs/react"
import { route } from "ziggy-js"
import { motion, AnimatePresence } from "framer-motion";

export default function AccountsIndex({ accounts, platforms, filters, accountCounts, currentUser }) {
  const t = useTranslate()
  const [accountList, setAccountList] = useState(accounts.data || [])
  const [searchQuery, setSearchQuery] = useState(filters?.search || "")
  const [platformFilter, setPlatformFilter] = useState(filters?.platform || "all")
  const [statusFilter, setStatusFilter] = useState(filters?.status || "all")
  const [userFilter, setUserFilter] = useState(filters?.user_filter || "mine")
  const [accountToDelete, setAccountToDelete] = useState(null)
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
  const [isConnectModalOpen, setIsConnectModalOpen] = useState(false)
  const [connectAccount, setConnectAccount] = useState(null)

  const breadcrumbs = [
    { label: t("Dashboard"), href: route("user.home") },
    { label: t("Accounts") }
  ]

  useEffect(() => {
    setAccountList(accounts.data || [])
  }, [accounts])

  // Platform validation helper
  const isValidPlatformConfig = (platform) => {
    // TikTok uses client_key instead of client_id
    const hasClientId = platform?.configuration?.client_id || platform?.configuration?.client_key;
    const hasClientSecret = platform?.configuration?.client_secret;
    return platform?.configuration && hasClientId && hasClientSecret;
  };

  // Account table configuration
  const columns = [
    {
      key: "id",
      label: "No",
      className: "w-16",
      cellClassName: "font-medium",
      render: (_item, index) => index + 1,
    },
    {
      key: "name",
      label: "Account",
      render: (account) => (
        <div className="flex items-center space-x-3">
          <Avatar className="h-10 w-10 bg-gradient-to-br from-primary/20 to-secondary/20 border border-gray-200 dark:border-gray-600">
            <AvatarImage src={account.avatar_url} alt={account.label || account.name} />
            <AvatarFallback className="bg-gradient-to-br from-primary to-secondary text-white font-semibold">
              {(account.label || account.name || account.username || 'A').charAt(0).toUpperCase()}
            </AvatarFallback>
          </Avatar>
          <div>
            {/* Show account label prominently if it exists */}
            {account.label ? (
              <>
                <div className="font-medium text-gray-900 dark:text-white">
                  {account.label}
                </div>
                <div className="text-sm text-gray-500 dark:text-gray-400">
                  {account.name || account.username} {account.username && `(@${account.username})`}
                </div>
              </>
            ) : (
              <>
                <div className="font-medium text-gray-900 dark:text-white">
                  {account.name || account.username}
                </div>
                {account.username && (
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    @{account.username}
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      ),
    },
    {
      key: "owner",
      label: "Account Owner",
      render: (account) => (
        <div className="flex items-center space-x-2">
          {account.user?.id === currentUser?.id ? (
            <div className="flex items-center space-x-2">
              <div className="p-1.5 bg-blue-100 dark:bg-blue-900/20 rounded-full">
                <Crown className="w-3 h-3 text-blue-600 dark:text-blue-400" />
              </div>
              <div>
                <div className="font-medium text-gray-900 dark:text-white text-sm">
                  You
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400">
                  Owner
                </div>
              </div>
            </div>
          ) : (
            <div className="flex items-center space-x-2">
              <div className="p-1.5 bg-gray-100 dark:bg-gray-800 rounded-full">
                <User className="w-3 h-3 text-gray-600 dark:text-gray-400" />
              </div>
              <div>
                <div className="font-medium text-gray-900 dark:text-white text-sm">
                  {account.user?.name || 'Unknown User'}
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400">
                  {account.user?.email || 'No email'}
                </div>
              </div>
            </div>
          )}
        </div>
      ),
    },
    {
      key: "platform",
      label: "Platform",
      render: (account) => (
        <div className="flex items-center space-x-3">
          <div className="p-2 bg-gradient-to-br from-gray-50 to-gray-100 dark:from-zinc-800 dark:to-zinc-700 rounded-lg">
            <PlatformIcon slug={account.platform?.slug} size={24} />
          </div>
          <span className="font-medium text-gray-900 dark:text-white capitalize">
            {account.platform?.name}
          </span>
        </div>
      ),
    },
    {
      key: "status",
      label: "Status",
      render: (account) => (
        <div className="flex items-center gap-3">
          <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${
            account.status === '1'
              ? 'bg-green-50 text-green-700 border border-green-200 dark:bg-green-900/20 dark:text-green-400 dark:border-green-800'
              : 'bg-red-50 text-red-700 border border-red-200 dark:bg-red-900/20 dark:text-red-400 dark:border-red-800'
          }`}>
            <div className={`w-2 h-2 rounded-full ${
              account.status === '1' ? 'bg-green-500' : 'bg-red-500'
            }`} />
            {account.status === '1' ? 'Active' : 'Inactive'}
          </span>
          <button
            className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
              account.status === '1'
                ? "bg-gradient-to-r from-green-500 to-green-600"
                : "bg-gray-300 dark:bg-gray-600"
            }`}
            onClick={() => handleToggleStatus(account.id)}
          >
            <span
              className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform shadow-sm ${
                account.status === '1' ? "translate-x-5" : "translate-x-1"
              }`}
            />
          </button>
        </div>
      ),
    },
    {
      key: "stats",
      label: "Stats",
      render: (account) => (
        <div className="text-sm text-gray-600 dark:text-gray-400">
          <div className="flex items-center gap-1">
            <Users className="w-3 h-3" />
            {account.followers || account.followers_count || 0}
          </div>
          <div className="text-xs text-gray-500 dark:text-gray-500 mt-0.5">
            Posts: {account.posts?.length || account.posts_count || 0}
          </div>
        </div>
      ),
    },
    {
      key: "created_at",
      label: "Connected",
      render: (account) => (
        <div className="text-sm text-gray-500 dark:text-gray-400">
          {new Date(account.created_at).toLocaleDateString()}
        </div>
      ),
    },
  ]

  const actionMenuItems = [
    { key: "view", label: "View Details", icon: Eye },
    { key: "connect", label: "Connect Account", icon: Link },
    { key: "settings", label: "Platform Settings", icon: Settings },
    { key: "delete", label: "Delete", icon: Trash2, className: "text-red-600 hover:text-red-700" },
  ]

  const filterOptions = [
    { label: "Active", value: "1" },
    { label: "Inactive", value: "0" },
  ]

  // Handlers
  const handleSearch = (value) => {
    setSearchQuery(value)
    router.get(route("user.platform.account.index"), {
      search: value,
      platform: platformFilter !== "all" ? platformFilter : undefined,
      status: statusFilter !== "all" ? statusFilter : undefined,
      user_filter: userFilter,
    }, { preserveState: true, replace: true })
  }

  const handlePlatformFilter = (value) => {
    setPlatformFilter(value)
    router.get(route("user.platform.account.index"), {
      search: searchQuery,
      platform: value !== "all" ? value : undefined,
      status: statusFilter !== "all" ? statusFilter : undefined,
      user_filter: userFilter,
    }, { preserveState: true, replace: true })
  }

  const handleStatusFilter = (value) => {
    setStatusFilter(value)
    router.get(route("user.platform.account.index"), {
      search: searchQuery,
      platform: platformFilter !== "all" ? platformFilter : undefined,
      status: value !== "all" ? value : undefined,
      user_filter: userFilter,
    }, { preserveState: true, replace: true })
  }

  const handleUserFilter = (value) => {
    setUserFilter(value)
    router.get(route("user.platform.account.index"), {
      search: searchQuery,
      platform: platformFilter !== "all" ? platformFilter : undefined,
      status: statusFilter !== "all" ? statusFilter : undefined,
      user_filter: value,
    }, { preserveState: true, replace: true })
  }

  const { handleToggle: handleAccountToggle } = useToggleHandler(
    "user.platform.account.status.update",
    (id, newStatus) => {
      setAccountList((prev) =>
        prev.map((account) =>
          account.id === id ? { ...account, status: newStatus } : account
        )
      );
    }
  )

  const handleToggleStatus = (accountId) => {
    const account = accountList.find((a) => a.id === accountId)
    if (account) {
      handleAccountToggle(accountId, String(account.status))
    }
  }

  const { handleDelete: handleAccountDelete, isDeleting } = useDeleteHandler(
    'user.platform.account.delete',
    (deletedId) => {
      setAccountList((prev) => prev.filter((a) => a.id !== deletedId))
      setIsDeleteModalOpen(false)
      setAccountToDelete(null)
    }
  )

  const { handleBulkAction } = useBulkHandler(
    "user.platform.account.bulk",
    (action, ids) => {
      setAccountList((prev) => {
        switch (action) {
          case "active":
            return prev.map((a) =>
              ids.includes(a.id) ? { ...a, status: "1" } : a
            )
          case "inactive":
            return prev.map((a) =>
              ids.includes(a.id) ? { ...a, status: "0" } : a
            )
          case "delete":
            return prev.filter((a) => !ids.includes(a.id))
          default:
            return prev
        }
      })
    }
  )

  const handleRowAction = (action, account) => {
    switch (action) {
      case 'view':
        // Navigate to the specific platform's accounts page to view details
        router.get(route("user.platform.accounts", account.platform_id))
        break
      case 'connect':
        // Check if platform is configured before connecting
        if (!isValidPlatformConfig(account.platform)) {
          // Show platform not configured error
          router.get(route("user.platform.setting", account.platform_id), {
            error: 'platform_not_configured'
          });
          return;
        }

        // Connect the account with proper flow - use window.location for OAuth redirects
        if (account.platform?.slug) {
          window.location.href = route("user.account.connect", {
            medium: account.platform.slug,
            account_id: account.id
          });
        }
        break
      case 'settings':
        // Navigate to platform settings
        router.get(route("user.platform.setting", account.platform_id))
        break
      case 'delete':
        setAccountToDelete(account)
        setIsDeleteModalOpen(true)
        break
    }
  }

  return (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="flex-1 p-6 overflow-auto bg-gradient-to-br from-gray-50 to-gray-100 dark:from-zinc-950 dark:to-black min-h-screen">
        {/* Header */}
        <div className="mb-6">
          <div className="flex items-center justify-between flex-wrap gap-4 mb-2">
            <div>
               <div className="flex items-center gap-3">
                <div>
                  <User className="h-6 w-6 text-primary" />
                </div>
                <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">
                  {t("All Accounts")}
                </h1>
              </div>
              <p className="text-gray-500 dark:text-gray-200">
                {t("Manage all your connected social media accounts across platforms")}
              </p>
            </div>

            {/* Create Account Button */}
            <Button
              onClick={() => setIsConnectModalOpen(true)}
              className="bg-gradient-to-r from-primary to-secondary text-white hover:from-secondary hover:to-primary shadow-sm hover:shadow-md transition-all duration-200"
              size="lg"
            >
              <Plus className="w-5 h-5 mr-2" />
              {t("Connect Account")}
            </Button>
          </div>
        </div>
     

        {/* Platform tabs - PRIMARY FILTER */}
        <div className="mb-6 overflow-hidden"> 
          <div className="overflow-x-auto">
            <div className="inline-flex bg-white dark:bg-zinc-900 rounded-lg p-1 gap-1 border border-gray-200 dark:border-zinc-800">
            <button
              onClick={() => handlePlatformFilter("all")}
              className={`rounded-md px-4 py-2 text-sm font-medium transition-colors min-w-[120px] ${
                platformFilter === "all"
                  ? "bg-gradient-to-r from-primary to-secondary text-white shadow-sm"
                  : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
              }`}
            >
              {t("All Platforms")}
            </button>
            {platforms.map((platform) => (
              <button
                key={platform.slug}
                onClick={() => handlePlatformFilter(platform.slug)}
                className={`rounded-md px-4 py-2 text-sm font-medium transition-colors ${
                  platformFilter === platform.slug
                    ? "bg-gradient-to-r from-primary to-secondary text-white shadow-sm"
                    : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                }`}
              >
                {platform.name}
              </button>
            ))}
          </div>
          </div>
        </div> 

        {/* Data Table - Without built-in search/filter */}
        <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
          >
            <DataTable
              data={accountList}
              propName="accounts"
              paginationData={accounts}
              columns={columns}
              searchFields={['name', 'username', 'label']}
              searchPlaceholder={t('Search accounts...')}
              filterOptions={filterOptions}
              actionMenuItems={actionMenuItems}
              onSearch={handleSearch}
              onFilterChange={handleStatusFilter}
              onBulkActive={(ids) => handleBulkAction("active", ids)}
              onBulkInactive={(ids) => handleBulkAction("inactive", ids)}
              onBulkDelete={(ids) => handleBulkAction("delete", ids)}
              onRowAction={handleRowAction}
              actionButton={ 
                <div className="flex items-center justify-between flex-wrap gap-4">
                  <div className="flex items-center gap-2 grow lg:w-auto w-full">
                    <Shield className="w-4 h-4 text-gray-500" />
                    <span className="text-sm text-gray-700 dark:text-gray-300">
                      Account Ownership {platformFilter !== "all" ? `(${platforms.find(p => p.slug === platformFilter)?.name || 'Selected Platform'})` : '(All Platforms)'}:
                    </span>
                  </div>
                  <div className="inline-flex bg-gray-100 dark:bg-zinc-800 rounded-lg p-1">
                    {(() => {
                      // Get current counts based on selected platform
                      const getCurrentCounts = () => {
                        if (platformFilter === "all") {
                          return accountCounts?.global || { mine: 0, others: 0, all: 0 };
                        }
                        return accountCounts?.platforms?.[platformFilter] || { mine: 0, others: 0, all: 0 };
                      };
                      const currentCounts = getCurrentCounts();

                      return (
                        <>
                          <button
                            onClick={() => handleUserFilter("mine")}
                            className={`rounded-md px-3 py-1.5 text-sm font-medium transition-colors flex items-center gap-2 ${
                              userFilter === "mine"
                                ? "bg-cyan-500 text-white shadow-sm"
                                : "text-gray-600 dark:text-gray-400 hover:bg-white dark:hover:bg-zinc-700 hover:text-gray-900 dark:hover:text-gray-100"
                            }`}
                          >
                            <Crown className="w-3.5 h-3.5" />
                            <span className="hidden sm:inline">My Accounts</span>
                            <span className="sm:hidden">Mine</span>
                            {currentCounts.mine > 0 && (
                              <span className={`ml-1 text-xs h-4 px-1.5 rounded-full font-medium ${
                                userFilter === "mine"
                                  ? "bg-white/20 text-white"
                                  : "bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300"
                              }`}>
                                {currentCounts.mine}
                              </span>
                            )}
                          </button>
                          <button
                            onClick={() => handleUserFilter("others")}
                            className={`rounded-md px-3 py-1.5 text-sm font-medium transition-colors flex items-center gap-2 ${
                              userFilter === "others"
                                ? "bg-amber-600 text-white shadow-sm"
                                : "text-gray-600 dark:text-gray-400 hover:bg-white dark:hover:bg-zinc-700 hover:text-gray-900 dark:hover:text-gray-100"
                            }`}
                          >
                            <Users className="w-3.5 h-3.5" />
                            <span className="hidden sm:inline">Others</span>
                            {currentCounts.others > 0 && (
                              <span className={`ml-1 text-xs h-4 px-1.5 rounded-full font-medium ${
                                userFilter === "others"
                                  ? "bg-white/20 text-white"
                                  : "bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300"
                              }`}>
                                {currentCounts.others}
                              </span>
                            )}
                          </button>
                          <button
                            onClick={() => handleUserFilter("all")}
                            className={`rounded-md px-3 py-1.5 text-sm font-medium transition-colors flex items-center gap-2 ${
                              userFilter === "all"
                                ? "bg-gray-600 text-white shadow-sm"
                                : "text-gray-600 dark:text-gray-400 hover:bg-white dark:hover:bg-zinc-700 hover:text-gray-900 dark:hover:text-gray-100"
                            }`}
                          >
                            <UserCircle className="w-3.5 h-3.5" />
                            <span className="hidden sm:inline">All</span>
                            {currentCounts.all > 0 && (
                              <span className={`ml-1 text-xs h-4 px-1.5 rounded-full font-medium ${
                                userFilter === "all"
                                  ? "bg-white/20 text-white"
                                  : "bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300"
                              }`}>
                                {currentCounts.all}
                              </span>
                            )}
                          </button>
                        </>
                      );
                    })()}
                  </div>
                </div> 
              }
            />
        </motion.div>
        

        {/* Delete Modal */}
        <DeleteModal
          isOpen={isDeleteModalOpen}
          onClose={() => setIsDeleteModalOpen(false)}
          title={t("Delete Account")}
          description={t("Are you sure you want to delete this account? This action cannot be undone.")}
          onConfirm={() => handleAccountDelete(accountToDelete?.id)}
          isDeleting={isDeleting}
        />

        {/* Connect Account Modal */}
        <ConnectAccountModal
          isOpen={isConnectModalOpen}
          onClose={() => setIsConnectModalOpen(false)}
          platforms={platforms}
          t={t}
        />
      </div>
    </AppLayout>
  )
}