"use client"

import { useState, useRef, useEffect } from "react"
import { Search, Filter, MoreVertical, Plus, Eye, Link, Settings, Trash2, Check } from "lucide-react"
import PlatformIcon from "@/Components/UI/PlatformIcon"
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"
import { route } from "ziggy-js"

const AccountSelection = ({
  t,
  onSelectedAccountsChange,
  onActivePlatformChange,
  accounts,
  selectedAccountIds,
  socialPlatforms = [],
  mode = "full", // "full" for Calendar, "simple" for AllPosts
  showAllPlatforms = false // Show all platforms regardless of available accounts
}) => {
  const [selectedAccounts, setSelectedAccounts] = useState([])
  const [searchTerm, setSearchTerm] = useState("")
  const [activePlatform, setActivePlatform] = useState("facebook")
  const [openContextMenus, setOpenContextMenus] = useState({})
  const [showFilterDropdown, setShowFilterDropdown] = useState(false)
  const [activeFilters, setActiveFilters] = useState({
    accountType: "all",
    status: "all",
  })

  const contextMenuRefs = useRef({})
  const filterDropdownRef = useRef(null)

  useEffect(() => {
    if (selectedAccountIds) {
      setSelectedAccounts(selectedAccountIds)
    }
  }, [selectedAccountIds])

  const filterOptions = {
    accountType: [
      { value: "all", label: "All Types" },
      { value: "profile", label: "Profile" },
      { value: "page", label: "Page" },
      { value: "group", label: "Group" },
      { value: "channel", label: "Channel" },
    ],
    status: [
      { value: "all", label: "All Status" },
      { value: "connected", label: "Connected" },
      { value: "disconnected", label: "Disconnected" },
    ],
  }

  // Filter accounts based on mode and search/filter criteria
  const filteredAccounts = mode === "simple"
    ? accounts // In simple mode, just show the accounts passed in (already filtered by parent)
    : accounts.filter((account) => {
        const matchesSearch =
          account?.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          account?.platform?.name?.toLowerCase().includes(searchTerm.toLowerCase())
        const matchesPlatform = account?.platform?.slug === activePlatform
        const matchesAccountType = activeFilters.accountType === "all" || account.accountType === activeFilters.accountType
        const matchesStatus = activeFilters.status === "all" || activeFilters.status === "connected"

        return matchesSearch && matchesPlatform && matchesAccountType && matchesStatus
      })

  // Get platforms to display
  const platformsToShow = showAllPlatforms
    ? socialPlatforms // Show all platforms when showAllPlatforms is true
    : socialPlatforms.filter(platform =>
        accounts.some(account => account.platform?.slug === platform.slug)
      ) // Only show platforms that have accounts

  const handleAccountToggle = (accountId) => {
    const account = accounts.find(a => a.id === accountId)

    let updatedSelectedAccounts
    if (selectedAccounts.includes(accountId)) {
      updatedSelectedAccounts = selectedAccounts.filter(id => id !== accountId)
    } else {
      updatedSelectedAccounts = [...selectedAccounts, accountId]
    }

    setSelectedAccounts(updatedSelectedAccounts)

    const selectedAccountObjects = accounts.filter(a => updatedSelectedAccounts.includes(a.id))
    onSelectedAccountsChange && onSelectedAccountsChange(selectedAccountObjects)
  }

  const handleSearchTermChange = (e) => {
    setSearchTerm(e.target.value)
  }

  const toggleContextMenu = (accountId) => {
    setOpenContextMenus(prev => ({
      ...prev,
      [accountId]: !prev[accountId]
    }))
  }

  const handleContextAction = (accountId, action) => {
    setOpenContextMenus(prev => ({
      ...prev,
      [accountId]: false
    }))
  }

  const handleFilterChange = (filterType, value) => {
    setActiveFilters(prev => ({
      ...prev,
      [filterType]: value
    }))
  }

  const clearFilters = () => {
    setActiveFilters({
      accountType: "all",
      status: "all",
    })
    setSearchTerm("")
  }

  const handlePlatformChange = (platformSlug) => {
    setActivePlatform(platformSlug)
    onActivePlatformChange && onActivePlatformChange(platformSlug)
  }

  // Close dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (filterDropdownRef.current && !filterDropdownRef.current.contains(event.target)) {
        setShowFilterDropdown(false)
      }

      Object.keys(contextMenuRefs.current).forEach(accountId => {
        if (contextMenuRefs.current[accountId] && !contextMenuRefs.current[accountId].contains(event.target)) {
          setOpenContextMenus(prev => ({
            ...prev,
            [accountId]: false
          }))
        }
      })
    }

    document.addEventListener("mousedown", handleClickOutside)
    return () => document.removeEventListener("mousedown", handleClickOutside)
  }, [])

  const activePLatfromId = socialPlatforms.find(
    sp => sp.slug === activePlatform
  )?.id || null

  // Render different modes
  if (mode === "simple") {
    return (
      <div className="w-full">
        {/* Simple Mode - Just accounts list */}
        <div className="space-y-2 min-h-[120px]">
          {filteredAccounts.map((account) => (
            <div
              key={account.id}
              className="flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-all duration-200 group"
            >
              {/* Checkbox */}
              <input
                type="checkbox"
                checked={selectedAccounts.includes(account.id)}
                onChange={() => handleAccountToggle(account.id)}
                className="w-4 h-4 text-primary bg-gray-100 border-gray-300 rounded focus:ring-primary dark:focus:ring-primary dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
              />

              {/* Avatar */}
              <div className="relative flex-shrink-0">
                <Avatar className="h-10 w-10">
                  <AvatarImage src={account.avatar} alt="User Avatar" />
                  <AvatarFallback>AV</AvatarFallback>
                </Avatar>
                {/* Platform Badge */}
                <div className="absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full bg-white dark:bg-zinc-900 flex items-center justify-center border-2 border-white dark:border-gray-900">
                  <PlatformIcon slug={account.platform?.slug} size={12} round={true} />
                </div>
              </div>

              {/* Account Info - Clean and simple */}
              <div className="flex-1 min-w-0">
                <h3 className="font-medium text-gray-900 dark:text-white text-sm truncate">
                  {account.label || account.name}
                </h3>
                <p className="text-xs text-gray-500 dark:text-gray-400 capitalize truncate">
                  {account.platform?.name} • {account.accountType || 'Account'}
                </p>
              </div>

              {/* Status Indicator */}
              <div className="flex-shrink-0">
                <div className={`w-2 h-2 rounded-full ${account.is_connected ? 'bg-green-500' : 'bg-gray-400'}`}></div>
              </div>
            </div>
          ))}

          {filteredAccounts.length === 0 && (
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <div className="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-center mb-3">
                <Check className="w-6 h-6 text-gray-400" />
              </div>
              <p className="text-gray-500 dark:text-gray-400 text-sm">
                {t ? t("No accounts available") : "No accounts available"}
              </p>
            </div>
          )}
        </div>
      </div>
    )
  }

  // Full Mode - Complete functionality for Calendar
  return (
    <div className="w-full bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-zinc-800">
        {/* Platform Tabs */}
        <div className="flex items-center gap-1 mb-4 bg-gray-100 dark:bg-gray-800 p-1 rounded-lg overflow-x-auto">
          {platformsToShow?.map((platform) => {
            const accountCount = accounts.filter(acc => acc.platform?.slug === platform.slug).length
            return (
            <button
              key={platform.slug}
              onClick={() => handlePlatformChange(platform.slug)}
              className={`whitespace-nowrap px-3 py-2 text-sm font-medium rounded-md transition-all flex items-center gap-2 ${
                activePlatform === platform.slug
                  ? "bg-white dark:bg-zinc-800 text-gray-900 dark:text-white shadow-sm"
                  : "text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
              }`}
            >
              <PlatformIcon slug={platform.slug} size={16} />
              <span>{platform.name}</span>
              {accountCount > 0 && (
                <span className="ml-1 text-xs bg-gray-200 dark:bg-gray-600 px-1.5 py-0.5 rounded-full">
                  {accountCount}
                </span>
              )}
            </button>
            )
          })}
        </div>

        {/* Search and Filter */}
        <div className="flex items-center gap-2">
          {/* Search Input */}
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder={t ? t("Search accounts...") : "Search accounts..."}
              value={searchTerm}
              onChange={handleSearchTermChange}
              className="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-zinc-900 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* Filter Dropdown */}
          <div className="relative" ref={filterDropdownRef}>
            <button
              onClick={() => setShowFilterDropdown(!showFilterDropdown)}
              className={`p-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors ${
                activeFilters.accountType !== "all" || activeFilters.status !== "all"
                  ? "bg-primary/10 dark:bg-primary/20 border-primary/30 dark:border-primary/60 text-primary dark:text-primary"
                  : "bg-white dark:bg-zinc-900 hover:bg-gray-50 dark:hover:bg-gray-700"
              }`}
            >
              <Filter className="w-4 h-4" />
            </button>

            {showFilterDropdown && (
              <div className="absolute right-0 top-full mt-1 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-lg shadow-lg z-20 min-w-[200px] py-2">
                {/* Account Type Filter */}
                <div className="px-3 py-2">
                  <h4 className="text-xs font-medium text-gray-900 dark:text-white mb-2">Account Type</h4>
                  {filterOptions.accountType.map((option) => (
                    <button
                      key={option.value}
                      onClick={() => handleFilterChange("accountType", option.value)}
                      className="w-full flex items-center justify-between px-2 py-1.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                    >
                      {option.label}
                      {activeFilters.accountType === option.value && (
                        <Check className="w-3 h-3 text-primary dark:text-primary" />
                      )}
                    </button>
                  ))}
                </div>

                <div className="border-t border-gray-200 dark:border-zinc-800"></div>

                {/* Status Filter */}
                <div className="px-3 py-2">
                  <h4 className="text-xs font-medium text-gray-900 dark:text-white mb-2">Status</h4>
                  {filterOptions.status.map((option) => (
                    <button
                      key={option.value}
                      onClick={() => handleFilterChange("status", option.value)}
                      className="w-full flex items-center justify-between px-2 py-1.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                    >
                      {option.label}
                      {activeFilters.status === option.value && (
                        <Check className="w-3 h-3 text-primary dark:text-primary" />
                      )}
                    </button>
                  ))}
                </div>

                {(activeFilters.accountType !== "all" || activeFilters.status !== "all") && (
                  <>
                    <div className="border-t border-gray-200 dark:border-zinc-800"></div>
                    <div className="px-3 py-2">
                      <button
                        onClick={clearFilters}
                        className="w-full px-2 py-1.5 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded"
                      >
                        Clear Filters
                      </button>
                    </div>
                  </>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Accounts List */}
      <div className="p-4 space-y-2 min-h-[120px]">
        {filteredAccounts.map((account) => (
          <div
            key={account.id}
            className="flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-all duration-200 group"
          >
            {/* Checkbox */}
            <input
              type="checkbox"
              checked={selectedAccounts.includes(account.id)}
              onChange={() => handleAccountToggle(account.id)}
              className="w-4 h-4 text-primary bg-gray-100 border-gray-300 rounded focus:ring-primary dark:focus:ring-primary dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
            />

            {/* Avatar */}
            <div className="relative flex-shrink-0">
              <Avatar className="h-10 w-10">
                <AvatarImage src={account.avatar} alt="User Avatar" />
                <AvatarFallback>AV</AvatarFallback>
              </Avatar>
              {/* Platform Badge */}
              <div className="absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full bg-white dark:bg-zinc-900 flex items-center justify-center border-2 border-white dark:border-gray-900">
                <PlatformIcon slug={account.platform?.slug} size={12} round={true} />
              </div>
            </div>

            {/* Account Info - Simplified without dropdown */}
            <div className="flex-1 min-w-0">
              <h3 className="font-medium text-gray-900 dark:text-white text-sm truncate">{account.label}</h3>
              <p className="text-xs text-gray-500 dark:text-gray-400 capitalize truncate">
                {account.name} {account.platform?.name} {account.accountType}
              </p>
            </div>

            {/* More Options with Context Menu */}
            <div className="relative flex-shrink-0" ref={(el) => (contextMenuRefs.current[account.id] = el)}>
              <button
                onClick={() => toggleContextMenu(account.id)}
                className="p-1.5 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
              >
                <MoreVertical className="w-4 h-4 text-gray-400" />
              </button>

              {/* Context Menu */}
              {openContextMenus[account.id] && (
                <div className="absolute right-0 top-full mt-1 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-lg shadow-lg z-10 min-w-[140px] py-1">
                  <button
                    onClick={() => handleContextAction(account.id, "view")}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                  >
                    <Eye className="w-4 h-4" />
                    View
                  </button>
                  <button
                    onClick={() => handleContextAction(account.id, "link")}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                  >
                    <Link className="w-4 h-4" />
                    Share
                  </button>
                  <button
                    onClick={() => handleContextAction(account.id, "settings")}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                  >
                    <Settings className="w-4 h-4" />
                    Settings
                  </button>
                  <div className="border-t border-gray-200 dark:border-zinc-800 my-1"></div>
                  <button
                    onClick={() => handleContextAction(account.id, "delete")}
                    className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20"
                  >
                    <Trash2 className="w-4 h-4" />
                    Delete
                  </button>
                </div>
              )}
            </div>
          </div>
        ))}

        {filteredAccounts.length === 0 && (
          <div className="flex flex-col items-center justify-center py-8 text-center">
            <div className="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-lg flex items-center justify-center mb-3">
              <Search className="w-6 h-6 text-gray-400" />
            </div>
            <p className="text-gray-500 dark:text-gray-400 text-sm">
              {searchTerm ?
                `No accounts found matching "${searchTerm}"` :
                "No accounts found"
              }
            </p>
          </div>
        )}
      </div>

      {/* Add Account Button */}
      <div className="p-4 pt-0">
        {activePLatfromId ? (
          <a href={route("user.platform.accounts", activePLatfromId)} className="w-full py-3 px-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 hover:border-primary/50 dark:hover:border-primary/60 hover:text-primary dark:hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 transition-all flex items-center justify-center gap-2 text-sm font-medium">
            <Plus className="w-4 h-4" />
            {t ? t("Add Account") : "Add Account"}
          </a>
        ) : (
          <a href={route("user.platform.index")} className="w-full py-3 px-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg text-gray-600 dark:text-gray-400 hover:border-primary/50 dark:hover:border-primary/60 hover:text-primary dark:hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 transition-all flex items-center justify-center gap-2 text-sm font-medium">
            <Plus className="w-4 h-4" />
            {t ? t("Connect Account") : "Connect Account"}
          </a>
        )}
      </div>
    </div>
  )
}

export default AccountSelection