"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { BellRinging, Checks, Phone, Envelope } from '@/lib/icons';
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { MatchBreakdownDialog } from "./match-breakdown-dialog";
import { markMatchNotifiedAction, markAllNotifiedAction } from "@/lib/appwrite/match-actions";
import type { Property, PropertyMatch, CustomerSearch, Customer } from "@/lib/appwrite/schema";

type Tab = "pending" | "all";

interface MatchesClientProps {
  matches: PropertyMatch[];
  customers: Customer[];
  properties: Property[];
  searches: CustomerSearch[];
}

function ScoreBadge({ score }: { score?: number | null }) {
  const s = score ?? 0;
  const color =
    s >= 80 ? "bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300"
    : s >= 60 ? "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"
    : s >= 40 ? "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-300"
    : "bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400";
  return (
    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold ${color}`}>
      {s}
    </span>
  );
}

export function MatchesClient({ matches, customers, properties, searches }: MatchesClientProps) {
  const router = useRouter();
  const [items, setItems] = useState(matches);
  const [tab, setTab] = useState<Tab>("pending");
  const [selectedMatch, setSelectedMatch] = useState<PropertyMatch | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [notifyingId, setNotifyingId] = useState<string | null>(null);
  const [notifyingAll, setNotifyingAll] = useState(false);

  const customerMap = Object.fromEntries(customers.map((c) => [c.$id, c]));
  const propertyMap = Object.fromEntries(properties.map((p) => [p.$id, p]));
  const searchMap = Object.fromEntries(searches.map((s) => [s.$id, s]));

  const pendingCount = items.filter((m) => m.notified !== true).length;
  const visible = tab === "pending" ? items.filter((m) => m.notified !== true) : items;

  function openBreakdown(m: PropertyMatch) {
    setSelectedMatch(m);
    setDialogOpen(true);
  }

  async function handleNotify(m: PropertyMatch) {
    setNotifyingId(m.$id);
    const result = await markMatchNotifiedAction(m.$id);
    setNotifyingId(null);
    if (result.ok) {
      setItems((prev) => prev.map((x) => x.$id === m.$id ? { ...x, notified: true } : x));
      router.refresh();
    } else {
      toast.error(result.error ?? "Güncelleme başarısız.");
    }
  }

  async function handleNotifyAll() {
    const pendingIds = items.filter((m) => !m.notified).map((m) => m.$id);
    if (pendingIds.length === 0) return;
    setNotifyingAll(true);
    const result = await markAllNotifiedAction(pendingIds);
    setNotifyingAll(false);
    if (result.ok) {
      setItems((prev) => prev.map((x) => ({ ...x, notified: true })));
      router.refresh();
      toast.success(`${pendingIds.length} eşleşme bildirildi olarak işaretlendi.`);
    } else {
      toast.error(result.error ?? "Toplu güncelleme başarısız.");
    }
  }

  return (
    <>
      <div className="flex flex-1 flex-col gap-4">
        {/* Header */}
        <div className="flex items-center justify-between gap-3 flex-wrap">
          <div>
            <h1 className="text-2xl font-bold">Eşleşmeler</h1>
            <p className="text-sm text-muted-foreground mt-0.5">
              {pendingCount > 0
                ? `${pendingCount} bildirilmemiş eşleşme`
                : "Tüm eşleşmeler bildirildi"}
            </p>
          </div>
          {pendingCount > 0 && (
            <Button size="sm" variant="outline" onClick={handleNotifyAll} disabled={notifyingAll}>
              <Checks className="mr-1.5 size-4" />
              Tümünü bildirildi işaretle
            </Button>
          )}
        </div>

        {/* Tabs */}
        <div className="flex gap-1 border-b">
          {(["pending", "all"] as Tab[]).map((key) => {
            const label = key === "pending" ? "Bekleyen" : "Tümü";
            const count = key === "pending" ? pendingCount : items.length;
            return (
              <button
                key={key}
                type="button"
                onClick={() => setTab(key)}
                className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${
                  tab === key
                    ? "border-primary text-foreground"
                    : "border-transparent text-muted-foreground hover:text-foreground"
                }`}
              >
                {label}
                <span className={`ml-1.5 text-xs rounded-full px-1.5 py-0.5 ${
                  tab === key ? "bg-primary/20 text-primary" : "bg-muted text-muted-foreground"
                }`}>
                  {count}
                </span>
              </button>
            );
          })}
        </div>

        {/* Table */}
        <div className="rounded-md border">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b bg-muted/30">
                <th className="p-3 text-left font-medium">Puan</th>
                <th className="p-3 text-left font-medium">Müşteri</th>
                <th className="p-3 text-left font-medium">İlan</th>
                <th className="p-3 text-left font-medium hidden md:table-cell">Tarih</th>
                <th className="p-3 text-left font-medium">Durum</th>
                <th className="p-3" />
              </tr>
            </thead>
            <tbody>
              {visible.length === 0 && (
                <tr>
                  <td colSpan={6} className="text-muted-foreground py-10 text-center">
                    {tab === "pending" ? "Bekleyen eşleşme yok." : "Henüz eşleşme yok."}
                  </td>
                </tr>
              )}
              {visible.map((m) => {
                const customer = customerMap[m.customerId];
                const property = propertyMap[m.propertyId];
                return (
                  <tr
                    key={m.$id}
                    className={`border-b last:border-0 ${
                      m.notified !== true ? "bg-amber-50/40 dark:bg-amber-950/10" : "hover:bg-muted/30"
                    }`}
                  >
                    <td className="p-3">
                      <ScoreBadge score={m.score} />
                    </td>
                    <td className="p-3 cursor-pointer" onClick={() => openBreakdown(m)}>
                      <p className="font-medium">{customer?.name ?? m.customerId}</p>
                      <div className="flex flex-col gap-0.5 mt-0.5" onClick={(e) => e.stopPropagation()}>
                        {customer?.phone && (
                          <a
                            href={`tel:${customer.phone}`}
                            className="flex items-center gap-1 text-xs text-foreground hover:text-primary transition-colors w-fit"
                          >
                            <Phone className="size-3 shrink-0" />
                            {customer.phone}
                          </a>
                        )}
                        {customer?.email && (
                          <a
                            href={`mailto:${customer.email}`}
                            className="flex items-center gap-1 text-xs text-muted-foreground hover:text-primary transition-colors w-fit"
                          >
                            <Envelope className="size-3 shrink-0" />
                            {customer.email}
                          </a>
                        )}
                      </div>
                    </td>
                    <td className="p-3 max-w-[200px]">
                      <Link
                        href={`/properties/${m.propertyId}`}
                        className="font-medium hover:text-primary hover:underline transition-colors truncate block"
                        onClick={(e) => e.stopPropagation()}
                      >
                        {property?.title ?? m.propertyId}
                      </Link>
                      {property?.city && (
                        <p className="text-xs text-muted-foreground">
                          {property.city}{property.district ? `, ${property.district}` : ""}
                        </p>
                      )}
                      {property?.price != null && (
                        <p className="text-xs font-medium text-foreground/80">
                          {property.price.toLocaleString("tr-TR")} {property.currency ?? "₺"}
                        </p>
                      )}
                    </td>
                    <td className="p-3 text-muted-foreground hidden md:table-cell">
                      {new Date(m.$createdAt).toLocaleDateString("tr-TR")}
                    </td>
                    <td className="p-3">
                      {m.notified === true ? (
                        <span className="text-xs text-muted-foreground flex items-center gap-1">
                          <Checks className="size-3.5 text-green-500" />
                          Bildirildi
                        </span>
                      ) : (
                        <span className="text-xs text-amber-600 font-medium flex items-center gap-1">
                          <BellRinging className="size-3.5" />
                          Bekliyor
                        </span>
                      )}
                    </td>
                    <td className="p-3">
                      {m.notified !== true && (
                        <Button
                          size="sm"
                          variant="ghost"
                          className="h-7 px-2 text-xs"
                          disabled={notifyingId === m.$id}
                          onClick={() => handleNotify(m)}
                        >
                          <BellRinging className="size-3 mr-1" />
                          Bildir
                        </Button>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {selectedMatch && (
        <MatchBreakdownDialog
          match={selectedMatch}
          property={propertyMap[selectedMatch.propertyId]}
          search={searchMap[selectedMatch.searchId]}
          customerName={customerMap[selectedMatch.customerId]?.name ?? selectedMatch.customerId}
          propertyTitle={propertyMap[selectedMatch.propertyId]?.title ?? selectedMatch.propertyId}
          open={dialogOpen}
          onOpenChange={setDialogOpen}
        />
      )}
    </>
  );
}
