"use client"

import * as React from "react"
import { Plus, X, Mail, Phone, Building2, Search } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  useGetDealContactsQuery,
  useLinkContactToDealMutation,
  useUnlinkContactFromDealMutation,
} from "@/api/rtk/contact-deal-api"
import { useGetContactsQuery } from "@/api/rtk/contacts-api"
import type { Contact } from "./types"
import { toast } from "sonner"
import { cn } from "@/lib/utils"

interface Props {
  dealId: string
}

export function DealContactsWidget({ dealId }: Props) {
  const [pickerOpen, setPickerOpen] = React.useState(false)
  const [search, setSearch] = React.useState("")

  const { data: linkedContacts = [], isLoading } = useGetDealContactsQuery(dealId)
  const { data: contactsResponse } = useGetContactsQuery({ limit: 100 }, { skip: !pickerOpen })
  const allContacts: Contact[] = contactsResponse?.data ?? []

  const [linkContact] = useLinkContactToDealMutation()
  const [unlinkContact] = useUnlinkContactFromDealMutation()

  const linkedIds = new Set(linkedContacts.map((c: any) => c.id))

  const filteredContacts = allContacts.filter((c) => {
    const q = search.toLowerCase()
    return (
      !linkedIds.has(c.id) &&
      (c.name.toLowerCase().includes(q) ||
        c.company.toLowerCase().includes(q) ||
        c.email.toLowerCase().includes(q))
    )
  })

  const handleLink = async (contactId: string) => {
    try {
      await linkContact({ dealId, contactId }).unwrap()
      toast.success("Contact linked")
    } catch (e: any) {
      toast.error(e?.data?.message ?? "Failed to link contact")
    }
  }

  const handleUnlink = async (contactId: string) => {
    try {
      await unlinkContact({ dealId, contactId }).unwrap()
      toast.success("Contact removed")
    } catch {
      toast.error("Failed to remove contact")
    }
  }

  return (
    <div className="flex flex-col gap-3">
      <div className="flex items-center justify-between">
        <span className="text-sm font-semibold">Linked Contacts</span>
        <Button
          size="sm"
          variant="outline"
          className="h-7 gap-1 text-xs"
          onClick={() => { setSearch(""); setPickerOpen(true) }}
        >
          <Plus className="size-3" />
          Link Contact
        </Button>
      </div>

      {isLoading ? (
        <p className="text-xs text-muted-foreground">Loading...</p>
      ) : linkedContacts.length === 0 ? (
        <p className="text-xs text-muted-foreground">No contacts linked yet.</p>
      ) : (
        <div className="flex flex-col gap-2">
          {linkedContacts.map((c: any) => (
            <div
              key={c.id}
              className="flex items-center gap-3 rounded-lg border bg-white p-3"
            >
              <div
                className="size-8 rounded-full flex items-center justify-center text-xs font-bold text-white shrink-0"
                style={{ backgroundColor: c.color ?? "#6C63FF" }}
              >
                {c.initials}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold truncate">{c.name}</p>
                <p className="text-xs text-muted-foreground truncate">{c.title} · {c.company}</p>
                <div className="flex items-center gap-3 mt-0.5">
                  {c.email && (
                    <span className="text-xs text-muted-foreground flex items-center gap-1">
                      <Mail className="size-3" />{c.email}
                    </span>
                  )}
                  {c.phone && (
                    <span className="text-xs text-muted-foreground flex items-center gap-1">
                      <Phone className="size-3" />{c.phone}
                    </span>
                  )}
                </div>
              </div>
              <Button
                variant="ghost"
                size="icon"
                className="size-7 text-muted-foreground hover:text-red-500 hover:bg-red-50 shrink-0"
                onClick={() => handleUnlink(c.id)}
              >
                <X className="size-3.5" />
              </Button>
            </div>
          ))}
        </div>
      )}

      {/* Contact picker dialog */}
      <Dialog open={pickerOpen} onOpenChange={setPickerOpen}>
        <DialogContent className="max-w-md">
          <DialogTitle>Link a Contact</DialogTitle>
          <div className="relative mt-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
            <Input
              type="search"
              className="pl-9"
              placeholder="Search by name, company or email..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              autoFocus
            />
          </div>
          <div className="flex flex-col gap-1.5 max-h-72 overflow-y-auto mt-1">
            {filteredContacts.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-6">
                {search ? "No contacts match your search." : "All contacts are already linked."}
              </p>
            ) : (
              filteredContacts.map((c) => (
                <button
                  key={c.id}
                  onClick={() => handleLink(c.id)}
                  className="flex items-center gap-3 rounded-lg p-2.5 hover:bg-slate-50 text-left transition-colors"
                >
                  <div
                    className="size-8 rounded-full flex items-center justify-center text-xs font-bold text-white shrink-0"
                    style={{ backgroundColor: c.color ?? "#6C63FF" }}
                  >
                    {c.initials}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold truncate">{c.name}</p>
                    <p className="text-xs text-muted-foreground truncate">{c.company} · {c.email}</p>
                  </div>
                  <Badge variant="secondary" className="text-[10px] shrink-0">{c.stage}</Badge>
                </button>
              ))
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
