"use client"

import { cn } from "@/lib/utils"
import * as React from "react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
    Dialog,
    DialogContent,
    DialogTitle,
} from "@/components/ui/dialog"
import { ReactSelect } from "@/components/ui/react-select"
import { Users, User, Loader2 } from "lucide-react"
import { toast } from "sonner"
import { useAppSelector } from "@/store/hooks"
import { useAuthToken } from "@/hooks/use-auth-token"
import { useCreateTeamMutation, useGetAllUsersQuery } from "@/api/rtk/teams-api"
import { useGetDivisionsQuery } from "@/api/rtk/divisions-api"
import { useInvalidateTeamsListCache } from "@/hooks/use-teams-query"

// Create Team Modal with searchable member selection

interface CreateTeamModalProps {
    isOpen: boolean
    onClose: () => void
}

function FieldLabel({ children }: { children: React.ReactNode }) {
    return (
        <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5 select-none">
            {children}
        </label>
    )
}

function SectionHeading({ icon, children }: { icon: React.ReactNode; children: React.ReactNode }) {
    return (
        <div className="flex items-center gap-2 mb-4">
            <div className="h-8 w-8 rounded-lg bg-[#6C63FF]/10 flex items-center justify-center text-[#6C63FF]">
                {icon}
            </div>
            <h3 className="text-[14px] font-black text-gray-900 uppercase tracking-wider font-['Lexend_Deca']">
                {children}
            </h3>
        </div>
    )
}

const PRESET_COLORS = [
    "#6C63FF", "#FF6B6B", "#4ECDC4", "#FFD93D", "#95E1D3",
    "#F38181", "#AA96DA", "#FCBAD3", "#A8E6CF", "#FFB6B9"
]

export function CreateTeamModal({ isOpen, onClose }: CreateTeamModalProps) {
    const { token: accessToken } = useAuthToken()
    const [name, setName] = React.useState("")
    const [divisionId, setDivisionId] = React.useState("")
    const [color, setColor] = React.useState(PRESET_COLORS[0])
    const [leadId, setLeadId] = React.useState<string>("")
    const [selectedMembers, setSelectedMembers] = React.useState<string[]>([])
    const [searchQuery, setSearchQuery] = React.useState("")
    const [showOnlySelected, setShowOnlySelected] = React.useState(false)
    const [createTeam, { isLoading }] = useCreateTeamMutation()
    const invalidateTeamsList = useInvalidateTeamsListCache()
    const { data: users = [], isLoading: isLoadingUsers } = useGetAllUsersQuery(undefined, { skip: !accessToken })
    const { data: divisions = [] } = useGetDivisionsQuery(undefined, { skip: !accessToken })

    // Filter out Admin users
    const nonAdminUsers = React.useMemo(() => {
        return users.filter(user => user.role?.name?.toLowerCase() !== 'admin')
    }, [users])

    const filteredUsers = React.useMemo(() => {
        return nonAdminUsers.filter(user => {
            const matchesSearch = user.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
                user.email?.toLowerCase().includes(searchQuery.toLowerCase())
            const matchesSelected = showOnlySelected ? selectedMembers.includes(user.id) : true
            return matchesSearch && matchesSelected
        })
    }, [nonAdminUsers, searchQuery, showOnlySelected, selectedMembers])

    React.useEffect(() => {
        if (isOpen) {
            setName("")
            setDivisionId("")
            setColor(PRESET_COLORS[0])
            setLeadId("")
            setSelectedMembers([])
            setSearchQuery("")
            setShowOnlySelected(false)
        }
    }, [isOpen])

    const handleSave = async () => {
        if (!name.trim()) {
            toast.error("Team name is required")
            return
        }
        if (!divisionId) {
            toast.error("Division is required")
            return
        }

        try {
            await createTeam({
                name: name.trim(),
                divisionId,
                color,
                lead: leadId || undefined,
                members: selectedMembers
            }).unwrap()

            await invalidateTeamsList()
            toast.success("Team created successfully")
            onClose()
        } catch (error: any) {
            console.error("Failed to create team:", error)
            toast.error(error?.data?.message || "Failed to create team")
        }
    }

    const toggleMember = (userId: string) => {
        setSelectedMembers(prev =>
            prev.includes(userId)
                ? prev.filter(id => id !== userId)
                : [...prev, userId]
        )
    }

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="sm:max-w-[600px] w-[96vw] max-h-[90vh] p-0 overflow-hidden animate-in zoom-in-95 duration-200">
                {/* HEADER */}
                <div className="relative overflow-hidden">
                    <div className="absolute inset-0 bg-gradient-to-br from-[#6C63FF] via-[#7C74FF] to-[#9B8FFF] opacity-100" />
                    <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,rgba(255,255,255,0.12),transparent_60%)]" />

                    <div className="relative px-7 py-5 flex items-start justify-between gap-4">
                        <div className="flex items-center gap-4 min-w-0">
                            <div className="h-12 w-12 rounded-xl bg-white/15 border border-white/25 backdrop-blur-sm flex items-center justify-center shrink-0 shadow-inner">
                                <Users size={22} className="text-white/90" />
                            </div>
                            <div className="min-w-0">
                                <DialogTitle className="text-[20px] font-extrabold text-white font-['Lexend'] leading-tight truncate">
                                    Create New Team
                                </DialogTitle>
                                <p className="text-[12px] text-white/75 font-medium mt-1">
                                    Build your sales team
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                {/* BODY */}
                <div className="overflow-y-auto max-h-[calc(90vh-200px)] scrollbar-themed px-7 py-6 space-y-6">
                    {/* Team Information */}
                    <section>
                        <SectionHeading icon={<Users size={14} />}>Team Information</SectionHeading>
                        <div className="space-y-4">
                            <div>
                                <FieldLabel>Division</FieldLabel>
                                <ReactSelect
                                    value={divisionId || "none"}
                                    onValueChange={(val) => setDivisionId(val === "none" ? "" : val)}
                                    options={[
                                        { value: "none", label: "Select division" },
                                        ...divisions.map((d) => ({
                                            value: d.id,
                                            label: d.name,
                                        })),
                                    ]}
                                    placeholder="Select division"
                                    aria-label="Division"
                                    triggerClassName="h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
                                />
                            </div>

                            <div>
                                <FieldLabel>Team Name</FieldLabel>
                                <Input
                                    className="h-10 text-[14px] font-semibold bg-gray-50 border-gray-200 rounded-xl"
                                    placeholder="e.g., Sales Team Alpha"
                                    value={name}
                                    onChange={(e) => setName(e.target.value)}
                                />
                            </div>

                            <div>
                                <FieldLabel>Team Color</FieldLabel>
                                <div className="flex items-center gap-2 flex-wrap">
                                    {PRESET_COLORS.map((c) => (
                                        <button
                                            key={c}
                                            onClick={() => setColor(c)}
                                            className={`h-10 w-10 rounded-lg transition-all ${color === c ? "ring-2 ring-offset-2 ring-gray-400 scale-110" : "hover:scale-105"
                                                }`}
                                            style={{ backgroundColor: c }}
                                        />
                                    ))}
                                </div>
                            </div>
                        </div>
                    </section>

                    {/* Team Lead */}
                    <section>
                        <SectionHeading icon={<User size={14} />}>Team Lead</SectionHeading>
                        <div>
                            <FieldLabel>Select Team Lead</FieldLabel>
                            <ReactSelect
                                value={leadId || "none"}
                                onValueChange={(val) => {
                                    const newLead = val === "none" ? "" : val
                                    if (newLead && !selectedMembers.includes(newLead)) {
                                        setSelectedMembers(prev => [...prev, newLead])
                                    }
                                    if (leadId && leadId !== newLead) {
                                        setSelectedMembers(prev => prev.filter(id => id !== leadId))
                                    }
                                    setLeadId(newLead)
                                }}
                                options={[
                                    { value: "none", label: "No lead assigned" },
                                    ...nonAdminUsers.map((user) => ({
                                        value: user.id,
                                        label: `${user.name} (${user.email})`,
                                    })),
                                ]}
                                placeholder="No lead assigned"
                                aria-label="Team lead"
                                triggerClassName="h-10 bg-gray-50 border-gray-200 rounded-xl text-[13px] font-semibold"
                            />
                        </div>
                    </section>

                    {/* Team Members */}
                    <section>
                        <SectionHeading icon={<Users size={14} />}>Team Members</SectionHeading>
                        {isLoadingUsers ? (
                            <div className="text-center py-4 text-sm text-gray-500">Loading users...</div>
                        ) : (
                            <>
                                <div className="flex items-center gap-3 mb-3">
                                    <div className="relative flex-1">
                                        <div className="absolute left-3 top-1/2 -translate-y-1/2">
                                            <Users size={14} className="text-gray-400" />
                                        </div>
                                        <Input
                                            type="search"
                                            className="h-9 pl-9 text-[12px] bg-gray-50/50 border-gray-100 rounded-xl"
                                            placeholder="Search members..."
                                            value={searchQuery}
                                            onChange={(e) => setSearchQuery(e.target.value)}
                                        />
                                    </div>
                                    <label className="flex items-center gap-2 cursor-pointer select-none group">
                                        <div 
                                            className={cn(
                                                "size-4 rounded border transition-all flex items-center justify-center",
                                                showOnlySelected 
                                                    ? "bg-[#6C63FF] border-[#6C63FF] text-white" 
                                                    : "bg-gray-50 border-gray-200 group-hover:border-[#6C63FF]/50"
                                            )}
                                            onClick={() => setShowOnlySelected(!showOnlySelected)}
                                        >
                                            <input
                                                type="checkbox"
                                                className="hidden"
                                                checked={showOnlySelected}
                                                onChange={() => {}}
                                            />
                                            {showOnlySelected && (
                                                <svg className="size-2.5 fill-current" viewBox="0 0 20 20">
                                                    <path d="M0 11l2-2 5 5L18 3l2 2L7 18z" />
                                                </svg>
                                            )}
                                        </div>
                                        <span className="text-[11px] font-bold text-gray-500 uppercase tracking-wider font-['Lexend_Deca'] group-hover:text-gray-700">
                                            Selected only
                                        </span>
                                    </label>
                                </div>
                                <div className="space-y-1 max-h-[400px] overflow-y-auto scrollbar-themed pr-1">
                                    {filteredUsers.map((user) => (
                                        <label
                                            key={user.id}
                                            className="member-item flex items-center gap-3 p-2.5 rounded-xl hover:bg-[#6C63FF]/5 cursor-pointer transition-all border border-transparent hover:border-[#6C63FF]/10 group shadow-sm hover:shadow-md mb-1"
                                        >
                                            <input
                                                type="checkbox"
                                                checked={selectedMembers.includes(user.id)}
                                                onChange={() => toggleMember(user.id)}
                                                className="h-4 w-4 rounded border-gray-300 text-[#6C63FF] focus:ring-[#6C63FF]"
                                            />
                                            <div className="relative h-8 w-8 rounded-full bg-gradient-to-br from-[#6C63FF] to-[#8B83FF] flex items-center justify-center text-white text-[11px] font-black shrink-0 overflow-hidden">
                                                {user.avatar?.url ? (
                                                    <Image src={user.avatar.url} alt={user.name} fill sizes="32px" className="object-cover" />
                                                ) : (
                                                    user.name?.slice(0, 2).toUpperCase()
                                                )}
                                            </div>
                                            <div className="flex-1 min-w-0">
                                                <p className="text-[13px] font-semibold text-gray-900 truncate">
                                                    {user.name}
                                                </p>
                                                <p className="text-[11px] text-gray-500 truncate">
                                                    {user.email}
                                                </p>
                                            </div>
                                        </label>
                                    ))}
                                </div>
                                <p className="text-[11px] text-gray-500 mt-2">
                                    {selectedMembers.length} member{selectedMembers.length !== 1 ? 's' : ''} selected
                                </p>
                            </>
                        )}
                    </section>
                </div>

                {/* FOOTER */}
                <div className="border-t border-gray-100 px-7 py-4 flex items-center justify-end gap-3 bg-gray-50/50">
                    <Button
                        variant="outlineModalAction"
                        onClick={onClose}
                        disabled={isLoading}
                    >
                        Cancel
                    </Button>
                    <Button
                        variant="accentModalAction"
                        onClick={handleSave}
                        disabled={isLoading}
                    >
                        {isLoading ? (
                            <>
                                <Loader2 size={15} className="animate-spin mr-2" />
                                Creating...
                            </>
                        ) : (
                            "Create Team"
                        )}
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    )
}
