"use client"
import React, { useState, useEffect } from "react"
import { Search, X, AlertCircle, Check, UserPlus, Users, Shield } from "lucide-react"
import Image from "next/image"
import { GitHubUserSearchResult } from "@/lib/types"
import { githubService } from "@/lib/services/github-service"

interface UserSearchModalProps {
  isOpen: boolean
  onClose: () => void
  onUserAdd: (
    user: GitHubUserSearchResult,
    role: "admin" | "member",
  ) => Promise<{ success: boolean; error?: string }>
  title?: string
  description?: string
  addButtonText?: string
  showRoleSelector?: boolean
}

// Compact Role Toggle Component (segmented control style)
const RoleToggle = ({
  selectedRole,
  onChange,
  disabled = false,
}: {
  selectedRole: "admin" | "member"
  onChange: (role: "admin" | "member") => void
  disabled?: boolean
}) => {
  return (
    <div
      className={`inline-flex items-center rounded-lg border border-border bg-muted/50 p-0.5 ${
        disabled ? "opacity-50 cursor-not-allowed" : ""
      }`}
    >
      <button
        type="button"
        onClick={() => !disabled && onChange("member")}
        disabled={disabled}
        title="Member: Can view repository data"
        className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-all duration-200 ${
          selectedRole === "member"
            ? "bg-background text-foreground shadow-sm"
            : "text-muted-foreground hover:text-foreground"
        } ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`}
      >
        <Users size={13} />
        <span>Member</span>
      </button>
      <button
        type="button"
        onClick={() => !disabled && onChange("admin")}
        disabled={disabled}
        title="Admin: Can manage members and settings"
        className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-all duration-200 ${
          selectedRole === "admin"
            ? "bg-blue-600 text-white shadow-sm"
            : "text-muted-foreground hover:text-foreground"
        } ${disabled ? "cursor-not-allowed" : "cursor-pointer"}`}
      >
        <Shield size={13} />
        <span>Admin</span>
      </button>
    </div>
  )
}

export const UserSearchModal: React.FC<UserSearchModalProps> = ({
  isOpen,
  onClose,
  onUserAdd,
  title = "Add Member",
  description = "Search for GitHub users to add",
  addButtonText = "Add Member",
  showRoleSelector = false,
}) => {
  const [searchQuery, setSearchQuery] = useState("")
  const [searchResults, setSearchResults] = useState<GitHubUserSearchResult[]>([])
  const [isSearching, setIsSearching] = useState(false)
  const [addingUser, setAddingUser] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  // Per-user role selections for inline role toggle
  const [userRoles, setUserRoles] = useState<Record<string, "admin" | "member">>({})

  const handleSearch = async () => {
    if (!searchQuery.trim()) {
      setError("Please enter a username to search")
      return
    }

    setIsSearching(true)
    setError(null)
    setSuccess(null)

    const result = await githubService.searchGitHubUsers(searchQuery)

    if (result.success && result.data) {
      setSearchResults(result.data)
      if (result.data.length === 0) {
        setError("No users found. Try a different username.")
      }
    } else {
      setError(result.error || "Failed to search users")
      setSearchResults([])
    }

    setIsSearching(false)
  }

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      handleSearch()
    }
  }

  const handleAddUser = async (user: GitHubUserSearchResult) => {
    setAddingUser(user.username)
    setError(null)
    setSuccess(null)

    // Get the role for this specific user (default to member)
    const roleToUse = showRoleSelector ? userRoles[user.username] || "member" : "member"
    const result = await onUserAdd(user, roleToUse)

    if (result.success) {
      setSuccess(
        `${user.username} has been added as ${roleToUse === "admin" ? "Admin" : "Member"}!`,
      )
      // Remove the added user from results
      setSearchResults(prev => prev.filter(u => u.username !== user.username))
      // Clean up their role selection
      setUserRoles(prev => {
        const newRoles = { ...prev }
        delete newRoles[user.username]
        return newRoles
      })

      // If no more results, clear search query
      if (searchResults.length === 1) {
        setSearchQuery("")
      }

      // Auto-dismiss success message after 3 seconds
      setTimeout(() => {
        setSuccess(null)
      }, 3000)
    } else {
      setError(result.error || "Failed to add member")
    }

    setAddingUser(null)
  }

  // Reset state when modal closes
  useEffect(() => {
    if (!isOpen) {
      setSearchQuery("")
      setSearchResults([])
      setError(null)
      setSuccess(null)
      setAddingUser(null)
      setUserRoles({})
    }
  }, [isOpen])

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-in fade-in duration-200">
      <div className="bg-card rounded-2xl w-full max-w-2xl max-h-[85vh] flex flex-col shadow-2xl border border-border animate-in slide-in-from-bottom-4 duration-300">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-border">
          <div>
            <h2 className="text-xl font-semibold flex items-center gap-2 text-foreground">
              <div className="p-2 rounded-lg bg-primary/10">
                <UserPlus size={20} className="text-primary" />
              </div>
              {title}
            </h2>
            <p className="text-sm text-muted-foreground mt-1">{description}</p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-accent rounded-lg transition-colors"
            aria-label="Close"
          >
            <X size={20} />
          </button>
        </div>

        {/* Search Input */}
        <div className="p-6 border-b border-border bg-accent/30">
          <div className="flex gap-2">
            <div className="relative flex-1">
              <Search
                size={18}
                className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground"
              />
              <input
                type="text"
                placeholder="Search GitHub username..."
                value={searchQuery}
                onChange={e => {
                  setSearchQuery(e.target.value)
                  setError(null)
                  setSuccess(null)
                }}
                onKeyPress={handleKeyPress}
                className="w-full pl-10 pr-4 py-2.5 bg-background border border-border rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all text-sm placeholder:text-muted-foreground"
                autoFocus
                disabled={!!addingUser || isSearching}
              />
            </div>
            <button
              onClick={handleSearch}
              disabled={!!addingUser || isSearching || !searchQuery.trim()}
              className="px-5 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 shadow-sm hover:shadow-md flex items-center gap-2"
            >
              {isSearching ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary-foreground"></div>
                  <span className="hidden sm:inline">Searching...</span>
                </>
              ) : (
                <>
                  <Search size={16} />
                  <span className="hidden sm:inline">Search</span>
                </>
              )}
            </button>
          </div>

          {/* Error Message */}
          {error && (
            <div className="mt-3 p-3 bg-destructive/10 border border-destructive/20 text-destructive rounded-lg text-sm flex items-start gap-2 animate-in slide-in-from-top-2">
              <AlertCircle size={16} className="flex-shrink-0 mt-0.5" />
              <span>{error}</span>
            </div>
          )}

          {/* Success Message */}
          {success && (
            <div className="mt-3 p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-700 dark:text-green-400 rounded-lg text-sm flex items-start gap-2 animate-in slide-in-from-top-2">
              <Check size={16} className="flex-shrink-0 mt-0.5" />
              <span>{success}</span>
            </div>
          )}
        </div>

        {/* Search Results */}
        <div className="flex-1 overflow-y-auto p-6">
          {searchResults.length > 0 ? (
            <div className="space-y-2">
              {searchResults.map(user => {
                const userRole = userRoles[user.username] || "member"
                return (
                  <div
                    key={user.username}
                    className="group flex items-center gap-3 p-3 border border-border rounded-xl hover:border-primary/50 hover:bg-accent/30 transition-all duration-200"
                  >
                    {/* User Avatar */}
                    <div className="flex-shrink-0">
                      <Image
                        src={user.avatarUrl}
                        alt={user.username}
                        width={40}
                        height={40}
                        className="rounded-full ring-2 ring-border group-hover:ring-primary/50 transition-all"
                      />
                    </div>

                    {/* Username */}
                    <div className="flex-1 min-w-0">
                      <div className="font-medium text-sm truncate text-foreground">
                        {user.username}
                      </div>
                    </div>

                    {/* Role Toggle + Add Button */}
                    <div className="flex items-center gap-2 flex-shrink-0">
                      {showRoleSelector && (
                        <RoleToggle
                          selectedRole={userRole}
                          onChange={role =>
                            setUserRoles(prev => ({ ...prev, [user.username]: role }))
                          }
                          disabled={!!addingUser}
                        />
                      )}
                      <button
                        onClick={() => handleAddUser(user)}
                        disabled={!!addingUser}
                        className="px-3 py-1.5 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 text-xs font-medium whitespace-nowrap shadow-sm hover:shadow-md flex items-center gap-1.5"
                      >
                        {addingUser === user.username ? (
                          <>
                            <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-primary-foreground"></div>
                            <span>Adding...</span>
                          </>
                        ) : (
                          <>
                            <UserPlus size={14} />
                            <span>{showRoleSelector ? "Add" : addButtonText}</span>
                          </>
                        )}
                      </button>
                    </div>
                  </div>
                )
              })}
            </div>
          ) : (
            <div className="text-center py-12">
              <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-accent mb-4">
                <Search size={32} className="text-muted-foreground" />
              </div>
              <p className="text-foreground font-medium">Ready to add a member</p>
              <p className="text-sm text-muted-foreground mt-1">
                Search for a GitHub user to add to your organization
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
