"use client";

import { useState } from "react";
import { Activity, Plus, Trash2, MessageCircle } from "lucide-react";
import { useImessageBridge } from "@/hooks/useImessageBridge";

const POLLING_MODES = [
  { id: "frequent", label: "Frequent", desc: "Every 3 seconds" },
  { id: "balanced", label: "Balanced", desc: "Every 10 seconds" },
  { id: "relaxed", label: "Relaxed", desc: "Every 30 seconds" },
] as const;

export function ImessageView() {
  const {
    settings,
    health,
    contacts,
    loading,
    updateSettings,
    addContact,
    removeContact,
  } = useImessageBridge();

  const [newName, setNewName] = useState("");
  const [newIdentifier, setNewIdentifier] = useState("");
  const [adding, setAdding] = useState(false);

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <p className="text-sm text-zinc-400">Loading iMessage settings...</p>
      </div>
    );
  }

  const handleAddContact = async () => {
    if (!newName.trim() || !newIdentifier.trim()) return;
    setAdding(true);
    await addContact(newName.trim(), newIdentifier.trim());
    setNewName("");
    setNewIdentifier("");
    setAdding(false);
  };

  const isOnline = health?.status === "running";

  return (
    <div className="h-full overflow-y-auto p-4 md:p-6">
      <div className="mx-auto max-w-2xl space-y-4 md:space-y-6">
        <div className="flex items-center gap-3">
          <MessageCircle size={24} className="text-zinc-600 dark:text-zinc-400" />
          <h1 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100">
            iMessage Bridge
          </h1>
        </div>

        {/* Service Status */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <div className="flex items-center gap-2">
            <Activity size={16} className="text-zinc-500" />
            <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
              Service Status
            </h2>
          </div>
          <div className="mt-3 flex items-center gap-2">
            <span
              className={`h-2 w-2 rounded-full ${
                isOnline ? "bg-green-500" : "bg-red-500"
              }`}
            />
            <span className="text-sm text-zinc-600 dark:text-zinc-400">
              {isOnline ? "Online" : "Offline"}
            </span>
            {health && (
              <span className="text-xs text-zinc-400 dark:text-zinc-500">
                — Polling: {health.polling_mode} · {health.contacts_count} contact
                {health.contacts_count !== 1 ? "s" : ""}
              </span>
            )}
          </div>
        </div>

        {/* Authorized Contacts */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
            Authorized Contacts
          </h2>
          <p className="mt-1 text-xs text-zinc-400">
            Only messages from these contacts will be routed to the AI agent.
          </p>

          <div className="mt-3 space-y-2">
            {contacts.map((c) => (
              <div
                key={c.id}
                className="flex items-center justify-between rounded-md bg-zinc-50 px-3 py-2 dark:bg-zinc-800"
              >
                <div>
                  <span className="text-sm font-medium text-zinc-800 dark:text-zinc-200">
                    {c.name}
                  </span>
                  <span className="ml-2 text-xs text-zinc-400">{c.identifier}</span>
                </div>
                <button
                  onClick={() => removeContact(c.id)}
                  className="text-zinc-400 transition-colors hover:text-red-500"
                >
                  <Trash2 size={14} />
                </button>
              </div>
            ))}

            {contacts.length === 0 && (
              <p className="text-xs text-zinc-400">No authorized contacts yet.</p>
            )}
          </div>

          <div className="mt-3 flex flex-col gap-2 sm:flex-row">
            <input
              type="text"
              placeholder="Name"
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              className="flex-1 rounded-md border border-zinc-300 bg-white px-2 py-2 text-sm text-zinc-900 placeholder-zinc-400 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-100"
            />
            <input
              type="text"
              placeholder="Phone or email"
              value={newIdentifier}
              onChange={(e) => setNewIdentifier(e.target.value)}
              className="flex-1 rounded-md border border-zinc-300 bg-white px-2 py-2 text-sm text-zinc-900 placeholder-zinc-400 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-100"
            />
            <button
              onClick={handleAddContact}
              disabled={adding || !newName.trim() || !newIdentifier.trim()}
              className="flex items-center justify-center gap-1 rounded-md bg-zinc-900 px-3 py-2 text-sm text-white transition-colors hover:bg-zinc-700 disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-zinc-300"
            >
              <Plus size={14} />
              Add
            </button>
          </div>
        </div>

        {/* Settings */}
        <div className="rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
          <h2 className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
            Settings
          </h2>

          <div className="mt-3">
            <label className="text-xs text-zinc-500 dark:text-zinc-400">
              Polling Interval
            </label>
            <div className="mt-1.5 flex gap-2">
              {POLLING_MODES.map((mode) => (
                <button
                  key={mode.id}
                  onClick={() => updateSettings({ polling_mode: mode.id })}
                  className={`flex-1 rounded-md border px-3 py-2 text-center text-sm transition-colors ${
                    settings?.polling_mode === mode.id
                      ? "border-zinc-900 bg-zinc-900 text-white dark:border-zinc-100 dark:bg-zinc-100 dark:text-zinc-900"
                      : "border-zinc-300 text-zinc-600 hover:border-zinc-400 dark:border-zinc-600 dark:text-zinc-400 dark:hover:border-zinc-500"
                  }`}
                >
                  <div className="font-medium">{mode.label}</div>
                  <div className="mt-0.5 text-xs opacity-70">{mode.desc}</div>
                </button>
              ))}
            </div>
          </div>

          <div className="mt-4">
            <label className="text-xs text-zinc-500 dark:text-zinc-400">
              Minimum Send Delay (seconds)
            </label>
            <input
              type="number"
              min={1}
              max={60}
              value={settings?.send_delay_seconds ?? 5}
              onChange={(e) =>
                updateSettings({ send_delay_seconds: Number(e.target.value) })
              }
              className="mt-1 w-24 rounded-md border border-zinc-300 bg-white px-2 py-1.5 text-sm text-zinc-900 dark:border-zinc-600 dark:bg-zinc-800 dark:text-zinc-100"
            />
          </div>
        </div>
      </div>
    </div>
  );
}
