"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { avatarUrl } from "@/lib/media";

interface Client {
  user_id: number;
  username: string | null;
  profile_photo: string | null;
  last_message_at: string;
  message_count: number;
  tags: string;
  notes: string;
}

export default function ClientCRMPage() {
  const { status } = useSession();
  const router = useRouter();
  const [clients, setClients] = useState<Client[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editTags, setEditTags] = useState("");
  const [editNotes, setEditNotes] = useState("");
  const [search, setSearch] = useState("");
  const [filterTag, setFilterTag] = useState("");

  useEffect(() => {
    if (status === "unauthenticated") router.push("/login");
  }, [status, router]);

  useEffect(() => {
    loadClients();
  }, []);

  async function loadClients() {
    try {
      const res = await fetch("/api/clients");
      if (res.ok) {
        const data = await res.json();
        setClients(data.data || []);
      }
    } catch {
      // silently fail
    } finally {
      setLoading(false);
    }
  }

  function startEdit(client: Client) {
    setEditingId(client.user_id);
    setEditTags(client.tags);
    setEditNotes(client.notes);
  }

  async function saveEdit(clientId: number) {
    try {
      await fetch("/api/clients", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ client_user_id: clientId, tags: editTags, notes: editNotes }),
      });

      setClients((prev) =>
        prev.map((c) =>
          c.user_id === clientId ? { ...c, tags: editTags, notes: editNotes } : c
        )
      );
      setEditingId(null);
    } catch {
      // silently fail
    }
  }

  // Collect all unique tags
  const allTags = Array.from(
    new Set(
      clients
        .flatMap((c) => c.tags.split(",").map((t) => t.trim()))
        .filter(Boolean)
    )
  );

  // Filter clients
  const filtered = clients.filter((c) => {
    const matchesSearch =
      !search ||
      (c.username?.toLowerCase() || "").includes(search.toLowerCase());
    const matchesTag =
      !filterTag ||
      c.tags
        .split(",")
        .map((t) => t.trim())
        .includes(filterTag);
    return matchesSearch && matchesTag;
  });

  if (status === "loading" || loading) {
    return (
      <div className="max-w-5xl mx-auto space-y-6">
        <div className="h-8 w-48 bg-surface-light rounded animate-pulse" />
        <div className="bg-surface rounded-xl p-6 animate-pulse space-y-3">
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className="h-16 bg-surface-light rounded" />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-5xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Client CRM</h1>
          <p className="text-text-muted text-sm mt-1">
            Manage your clients, add tags and notes for easy organization.
          </p>
        </div>
        <span className="text-sm text-text-muted">{clients.length} clients</span>
      </div>

      {/* Filters */}
      <div className="flex gap-3 flex-wrap">
        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search by username..."
          className="rounded-lg border border-white/10 bg-surface px-4 py-2 text-text placeholder-text-muted focus:border-primary focus:outline-none text-sm"
        />
        {allTags.length > 0 && (
          <select
            value={filterTag}
            onChange={(e) => setFilterTag(e.target.value)}
            className="rounded-lg border border-white/10 bg-surface px-4 py-2 text-text focus:border-primary focus:outline-none text-sm"
          >
            <option value="">All tags</option>
            {allTags.map((tag) => (
              <option key={tag} value={tag}>{tag}</option>
            ))}
          </select>
        )}
      </div>

      {/* Client table */}
      <div className="bg-surface rounded-xl border border-white/5 overflow-hidden">
        {filtered.length === 0 ? (
          <div className="p-8 text-center text-text-muted text-sm">
            {clients.length === 0 ? "No clients yet." : "No clients match your filters."}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/5 text-left text-xs text-text-muted uppercase tracking-wider">
                  <th className="px-4 py-3">Client</th>
                  <th className="px-4 py-3">Last Message</th>
                  <th className="px-4 py-3">Messages</th>
                  <th className="px-4 py-3">Tags</th>
                  <th className="px-4 py-3">Notes</th>
                  <th className="px-4 py-3 w-20"></th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((client) => (
                  <tr key={client.user_id} className="border-b border-white/5 hover:bg-surface-light/50 transition-colors">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <img
                          src={avatarUrl(client.profile_photo)}
                          alt=""
                          className="w-9 h-9 rounded-full object-cover ring-1 ring-white/10"
                        />
                        <span className="font-medium text-text text-sm">
                          {client.username || `User #${client.user_id}`}
                        </span>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-sm text-text-muted">
                      {new Date(client.last_message_at).toLocaleDateString()}
                    </td>
                    <td className="px-4 py-3 text-sm text-text-muted">
                      {client.message_count}
                    </td>
                    <td className="px-4 py-3">
                      {editingId === client.user_id ? (
                        <input
                          type="text"
                          value={editTags}
                          onChange={(e) => setEditTags(e.target.value)}
                          placeholder="tag1, tag2..."
                          className="w-full rounded border border-white/10 bg-surface-light px-2 py-1 text-sm text-text focus:border-primary focus:outline-none"
                        />
                      ) : (
                        <div className="flex flex-wrap gap-1">
                          {client.tags
                            .split(",")
                            .map((t) => t.trim())
                            .filter(Boolean)
                            .map((tag) => (
                              <span
                                key={tag}
                                className="bg-primary/10 text-primary text-xs px-2 py-0.5 rounded-full"
                              >
                                {tag}
                              </span>
                            ))}
                        </div>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      {editingId === client.user_id ? (
                        <input
                          type="text"
                          value={editNotes}
                          onChange={(e) => setEditNotes(e.target.value)}
                          placeholder="Notes..."
                          className="w-full rounded border border-white/10 bg-surface-light px-2 py-1 text-sm text-text focus:border-primary focus:outline-none"
                        />
                      ) : (
                        <span className="text-sm text-text-muted line-clamp-1">
                          {client.notes || "-"}
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      {editingId === client.user_id ? (
                        <div className="flex gap-1">
                          <button
                            onClick={() => saveEdit(client.user_id)}
                            className="text-green-400 hover:text-green-300 text-xs font-medium"
                          >
                            Save
                          </button>
                          <button
                            onClick={() => setEditingId(null)}
                            className="text-text-muted hover:text-text text-xs"
                          >
                            Cancel
                          </button>
                        </div>
                      ) : (
                        <button
                          onClick={() => startEdit(client)}
                          className="text-primary hover:text-primary-light text-xs font-medium transition-colors"
                        >
                          Edit
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
