"use client"
import React, { useState, useEffect, useCallback, useRef } from "react"
import { Users, UserPlus, RefreshCw, AlertCircle, Building2 } from "lucide-react"
import { ConfirmDialog } from "@/components/confirm-dialog"
import { MembersSkeleton } from "@/components/members/MembersSkeleton"
import { GitHubUserSearchResult, Member } from "@/lib/types"
import {
  addOrganizationMember,
  updateOrganizationMemberRole,
  removeOrganizationMember,
} from "./action"
import { useViewMode } from "@/app/app/ViewModeContext"
import { MembersList } from "@/components/members/members-list"
import { UserSearchModal } from "@/components/members/user-search-modal"
import { getMembersPageInitData } from "./data"

export interface MembersClientProps {
  initialUserId: string
  initialOrgId: string | null
  initialMembers: Member[]
  initialUserRole: string | null
}

export function MembersClient({
  initialUserId,
  initialOrgId,
  initialMembers,
  initialUserRole,
}: MembersClientProps) {
  const { currentOrg } = useViewMode()
  const initialOrgIdRef = useRef(initialOrgId)

  const [members, setMembers] = useState<Member[]>(initialMembers)
  const [currentUserId] = useState<string>(initialUserId)
  const [currentUserRole, setCurrentUserRole] = useState<string | null>(initialUserRole)
  const [loading, setLoading] = useState(!initialOrgId)
  const [showAddModal, setShowAddModal] = useState(false)
  const [error, setError] = useState<string | null>(
    !initialOrgId ? "No organization selected" : null,
  )
  const [updatingMember, setUpdatingMember] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState("")
  const [filterRole, setFilterRole] = useState<"all" | "owner" | "admin" | "member">("all")
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean
    memberId: string
    memberUsername: string
  } | null>(null)

  const isAdmin = currentUserRole === "admin" || currentUserRole === "owner"

  const fetchMembers = useCallback(async () => {
    if (!currentOrg?.id) {
      setError("No organization selected")
      setLoading(false)
      return
    }

    if (!isRefreshing) {
      setLoading(true)
    }
    setError(null)

    try {
      const initData = await getMembersPageInitData()

      if (!initData || initData.orgId !== currentOrg.id) {
        setCurrentUserRole(null)
        setMembers([])
        setError("Failed to load members")
      } else {
        setCurrentUserRole(initData.currentUserRole)
        setMembers(initData.members)
      }
    } catch (err) {
      console.error("Failed to fetch members:", err)
      setError("Failed to load members. Please try again.")
    } finally {
      setLoading(false)
      setIsRefreshing(false)
    }
  }, [currentOrg?.id, isRefreshing])

  // Only refetch when org changes from what the server provided
  useEffect(() => {
    if (!currentOrg?.id) {
      setError("No organization selected")
      setLoading(false)
      return
    }

    if (currentOrg.id === initialOrgIdRef.current) return
    initialOrgIdRef.current = currentOrg.id
    fetchMembers()
  }, [currentOrg?.id, fetchMembers])

  useEffect(() => {
    if (success) {
      const timer = setTimeout(() => setSuccess(null), 5000)
      return () => clearTimeout(timer)
    }
  }, [success])

  const handleMemberAdded = async () => {
    setIsRefreshing(true)
    await fetchMembers()
    setSuccess("Member added successfully!")
  }

  const handleUserAdd = async (user: GitHubUserSearchResult, role: "admin" | "member") => {
    if (!currentOrg?.id) {
      return { success: false, error: "No organization selected" }
    }

    const result = await addOrganizationMember(user, role, currentOrg.id)
    if (result.success) {
      handleMemberAdded()
    }
    return result
  }

  const handleUpdateRole = async (memberId: string, newRole: "admin" | "member" | "owner") => {
    if (!currentOrg?.id) return

    setUpdatingMember(memberId)
    setError(null)
    setSuccess(null)

    const result = await updateOrganizationMemberRole(currentOrg.id, memberId, newRole)

    if (result.success) {
      setSuccess("Member role updated successfully")
      setIsRefreshing(true)
      await fetchMembers()
    } else {
      setError(result.error || "Failed to update role")
    }

    setUpdatingMember(null)
  }

  const handleRemoveMember = async (memberId: string, memberUsername: string) => {
    if (!currentOrg?.id) return
    setConfirmDialog({ open: true, memberId, memberUsername })
  }

  const confirmRemoveMember = async () => {
    if (!confirmDialog || !currentOrg?.id) return

    const { memberId, memberUsername } = confirmDialog

    setUpdatingMember(memberId)
    setError(null)
    setSuccess(null)

    const result = await removeOrganizationMember(currentOrg.id, memberId)

    if (result.success) {
      setSuccess(`${memberUsername} has been removed successfully`)
      setIsRefreshing(true)
      await fetchMembers()
    } else {
      setError(result.error || "Failed to remove member")
    }

    setUpdatingMember(null)
    setConfirmDialog(null)
  }

  if (loading) {
    return <MembersSkeleton count={6} />
  }

  if (!currentOrg?.id) {
    return (
      <div className="flex justify-center items-center min-h-[70vh] p-4">
        <div className="bg-destructive/10 border border-destructive/20 text-destructive p-6 sm:p-8 rounded-2xl w-full max-w-md shadow-lg">
          <div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-destructive/20 mb-4">
            <AlertCircle size={24} />
          </div>
          <h3 className="text-base sm:text-lg font-semibold mb-2">No Organization Selected</h3>
          <p className="mb-4 text-sm sm:text-base opacity-90">
            Please select an organization from the sidebar
          </p>
        </div>
      </div>
    )
  }

  if (error && members.length === 0) {
    return (
      <div className="flex justify-center items-center min-h-[70vh] p-4">
        <div className="bg-destructive/10 border border-destructive/20 text-destructive p-6 sm:p-8 rounded-2xl w-full max-w-md shadow-lg">
          <div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-destructive/20 mb-4">
            <AlertCircle size={24} />
          </div>
          <h3 className="text-base sm:text-lg font-semibold mb-2">Unable to Load Members</h3>
          <p className="mb-4 text-sm sm:text-base opacity-90">{error}</p>
          <button
            onClick={() => fetchMembers()}
            className="flex items-center gap-2 w-full justify-center px-4 py-2.5 bg-destructive hover:bg-destructive/90 text-destructive-foreground rounded-xl text-sm font-medium transition-all shadow-sm hover:shadow-md"
          >
            <RefreshCw size={16} /> Try Again
          </button>
        </div>
      </div>
    )
  }

  const adminCount = members.filter(m => m.role === "admin" || m.role === "owner").length
  const memberCount = members.filter(m => m.role === "member").length

  return (
    <div className="flex-1 bg-background">
      <div className="h-screen py-6 sm:py-8 px-4 sm:px-6 max-w-[1400px] mx-auto">
        {/* Header */}
        <div className="mb-6 sm:mb-8">
          <div className="flex items-start justify-between gap-4 mb-2">
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold text-foreground flex items-center gap-3">
                <div className="p-2.5 rounded-xl bg-primary/10">
                  <Users size={28} className="text-primary" />
                </div>
                Organization Members
              </h1>
              <p className="text-muted-foreground mt-2">
                Manage members and their roles in your organization
              </p>
            </div>
            {isAdmin && (
              <button
                onClick={() => setShowAddModal(true)}
                disabled={showAddModal}
                className="flex items-center gap-2 px-4 py-2.5 bg-primary text-primary-foreground rounded-xl hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 text-sm font-medium whitespace-nowrap flex-shrink-0 shadow-sm hover:shadow-md"
              >
                <UserPlus size={16} />
                <span className="hidden sm:inline">Add Member</span>
                <span className="sm:hidden">Add</span>
              </button>
            )}
          </div>
        </div>

        <div className="bg-card rounded-2xl border border-border shadow-sm overflow-hidden">
          <MembersList
            members={members}
            currentUserId={currentUserId}
            isAdmin={isAdmin}
            updatingMember={updatingMember}
            error={error}
            success={success}
            searchQuery={searchQuery}
            filterRole={filterRole}
            onSearchChange={setSearchQuery}
            onFilterChange={setFilterRole}
            onUpdateRole={handleUpdateRole}
            onRemove={handleRemoveMember}
            onDismissError={() => setError(null)}
            onDismissSuccess={() => setSuccess(null)}
            headerIcon={<Building2 size={20} className="text-primary" />}
            headerTitle="Members"
            headerStats={`${members.length} ${members.length === 1 ? "member" : "members"} • ${adminCount} ${adminCount === 1 ? "admin" : "admins"} • ${memberCount} ${memberCount === 1 ? "member" : "members"}`}
          />
        </div>

        <UserSearchModal
          isOpen={showAddModal}
          onClose={() => setShowAddModal(false)}
          onUserAdd={handleUserAdd}
          title="Add Organization Member"
          description="Search for GitHub users and add them to this organization"
          showRoleSelector={true}
        />

        <ConfirmDialog
          open={confirmDialog?.open || false}
          onOpenChange={open => !open && setConfirmDialog(null)}
          onConfirm={confirmRemoveMember}
          title="Remove Member"
          description={`Are you sure you want to remove ${confirmDialog?.memberUsername} from this organization? This action cannot be undone.`}
          confirmText="Remove"
          cancelText="Cancel"
          variant="destructive"
        />
      </div>
    </div>
  )
}
