"use client";

import { useState, useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import VerificationStamp from "./VerificationStamp";
import { useAuth } from "@/lib/auth-context";
import { clientExecute } from "@/lib/api/client";
import { ApiError } from "@/lib/api/shared";
import { Spinner } from "@/components/Loading";
import type { Landlord } from "@/lib/types";

interface PropertyContactCardProps {
  landlord: Landlord | undefined;
  propertyTitle: string;
  propertyId: string;
}

type Modal = null | "viewing" | "message";

function Toast({ message, onClose }: { message: string; onClose: () => void }) {
  return (
    <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-forest text-white text-sm font-medium px-6 py-3 rounded-pill shadow-card-hover flex items-center gap-4">
      ✓ {message}
      <button onClick={onClose} className="opacity-70 hover:opacity-100 text-lg leading-none">×</button>
    </div>
  );
}

export default function PropertyContactCard({ landlord, propertyTitle, propertyId }: PropertyContactCardProps) {
  const { user } = useAuth();
  const router = useRouter();
  const pathname = usePathname();

  const [modal, setModal] = useState<Modal>(null);
  const [saved, setSaved] = useState(false);
  const [viewingDate, setViewingDate] = useState("");
  const [viewingNote, setViewingNote] = useState("");
  const [messageText, setMessageText] = useState("");
  const [toast, setToast] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  function showToast(msg: string) {
    setToast(msg);
    setTimeout(() => setToast(null), 3500);
  }

  useEffect(() => {
    if (!user) { setSaved(false); return; }
    let active = true;
    clientExecute<{ items: { id: string }[] }>("saved-property.list")
      .then((res) => { if (active) setSaved(res.items.some((p) => p.id === propertyId)); })
      .catch(() => { /* ignore */ });
    return () => { active = false; };
  }, [user, propertyId]);

  function requireAuthOr(open: Modal) {
    if (!user) {
      router.push(`/login?next=${encodeURIComponent(pathname)}`);
      return;
    }
    setError(null);
    setModal(open);
  }

  async function submitViewing() {
    if (!viewingDate) return;
    setBusy(true);
    setError(null);
    try {
      await clientExecute("viewing-request.create", {
        propertyId,
        preferredDate: viewingDate,
        note: viewingNote || undefined,
      });
      setModal(null);
      setViewingDate("");
      setViewingNote("");
      showToast(`Viewing requested for ${propertyTitle}. The landlord will respond within Villa.`);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Couldn't send the request. Please try again.");
    } finally {
      setBusy(false);
    }
  }

  async function submitMessage() {
    if (!messageText.trim()) return;
    setBusy(true);
    setError(null);
    try {
      await clientExecute("message.send", {
        landlordId: landlord?.id,
        propertyId,
        text: messageText.trim(),
      });
      setModal(null);
      setMessageText("");
      showToast(`Message sent to ${landlord?.name ?? "landlord"}`);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Couldn't send the message. Please try again.");
    } finally {
      setBusy(false);
    }
  }

  async function toggleSave() {
    if (!user) {
      router.push(`/login?next=${encodeURIComponent(pathname)}`);
      return;
    }
    const previous = saved;
    const next = !saved;
    setSaved(next);
    try {
      const res = await clientExecute<{ saved: boolean }>("saved-property.toggle", { propertyId });
      setSaved(res.saved);
      showToast(res.saved ? `${propertyTitle} saved to your list` : `${propertyTitle} removed from saved`);
    } catch {
      setSaved(previous);
      showToast("Couldn't update your saved list. Please try again.");
    }
  }

  const inputCls = "w-full border border-mist rounded-sm px-4 py-3 text-sm bg-white text-ink focus:outline-2 focus:outline-gold focus:border-forest";

  return (
    <>
      <aside className="bg-white border border-mist rounded-md p-5 lg:sticky lg:top-[96px]">
        <VerificationStamp
          variant={landlord?.verified ? "landlord" : "pending"}
          size={64}
          className="mb-4"
        />
        <h3 className="text-lg font-display font-semibold text-forest-deep mb-1">
          Listed by {landlord?.name ?? "Villa landlord"}
        </h3>
        <div className="text-sm text-ink-soft mb-4">
          {landlord?.verified ? "Verified landlord" : "Verification pending"} ·{" "}
          {landlord?.listingCount} active listing{landlord?.listingCount === 1 ? "" : "s"}
        </div>

        <button
          onClick={() => requireAuthOr("viewing")}
          className="block w-full text-center font-semibold text-sm px-6 py-3 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors mb-3"
        >
          Request a viewing
        </button>
        <button
          onClick={() => requireAuthOr("message")}
          className="block w-full text-center font-semibold text-sm px-6 py-3 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors mb-3"
        >
          Message landlord
        </button>
        <button
          onClick={toggleSave}
          className={`block w-full text-center font-semibold text-sm px-6 py-3 rounded-pill border transition-colors mb-5 ${
            saved
              ? "bg-[#E8F2EC] border-forest text-forest"
              : "border-mist text-forest hover:bg-forest hover:border-forest hover:text-white"
          }`}
        >
          {saved ? "✓ Saved" : "Save property"}
        </button>

        <ul className="flex flex-col gap-3">
          <li className="flex justify-between text-sm pb-3 border-b border-mist">
            <span className="text-ink-soft">Response time</span>
            <span className="font-mono font-medium">{landlord?.responseTime ?? "—"}</span>
          </li>
          <li className="flex justify-between text-sm">
            <span className="text-ink-soft">Phone verified</span>
            <span className="font-mono font-medium">{landlord?.verified ? "Yes" : "Pending"}</span>
          </li>
        </ul>
      </aside>

      {/* Request viewing modal */}
      {modal === "viewing" && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink/40 backdrop-blur-sm px-4">
          <div className="bg-white rounded-lg border border-mist shadow-card-hover w-full max-w-md">
            <div className="flex justify-between items-center px-6 py-4 border-b border-mist">
              <h3 className="font-display font-semibold text-lg text-forest-deep">Request a viewing</h3>
              <button onClick={() => setModal(null)} className="text-ink-soft hover:text-ink text-2xl leading-none">×</button>
            </div>
            <div className="p-6 flex flex-col gap-4">
              <div className="bg-sage border border-mist rounded-sm px-4 py-3 text-sm text-ink-soft">
                <span className="font-semibold text-ink">{propertyTitle}</span>
              </div>
              <div className="flex flex-col gap-2">
                <label className="font-mono text-xs uppercase tracking-widest text-ink-soft">Preferred date</label>
                <input type="date" value={viewingDate} onChange={(e) => setViewingDate(e.target.value)} className={inputCls} />
              </div>
              <div className="flex flex-col gap-2">
                <label className="font-mono text-xs uppercase tracking-widest text-ink-soft">Note (optional)</label>
                <textarea
                  value={viewingNote}
                  onChange={(e) => setViewingNote(e.target.value)}
                  placeholder="Any details to share with the landlord…"
                  rows={3}
                  className={`${inputCls} resize-none`}
                />
              </div>
              {error && <p className="text-sm text-red-600">{error}</p>}
            </div>
            <div className="px-6 pb-5 flex gap-3 justify-end">
              <button onClick={() => setModal(null)}
                className="inline-flex items-center justify-center font-semibold text-sm px-5 py-2 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors">
                Cancel
              </button>
              <button
                onClick={submitViewing}
                disabled={busy || !viewingDate}
                className="inline-flex items-center justify-center gap-2 font-semibold text-sm px-5 py-2 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors disabled:opacity-40"
              >
                {busy ? <><Spinner size="sm" />Sending…</> : "Send request"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Message landlord modal */}
      {modal === "message" && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink/40 backdrop-blur-sm px-4">
          <div className="bg-white rounded-lg border border-mist shadow-card-hover w-full max-w-md">
            <div className="flex justify-between items-center px-6 py-4 border-b border-mist">
              <h3 className="font-display font-semibold text-lg text-forest-deep">
                Message {landlord?.name ?? "landlord"}
              </h3>
              <button onClick={() => setModal(null)} className="text-ink-soft hover:text-ink text-2xl leading-none">×</button>
            </div>
            <div className="p-6 flex flex-col gap-4">
              <div className="bg-sage border border-mist rounded-sm px-4 py-3 text-sm text-ink-soft">
                Re: <span className="font-semibold text-ink">{propertyTitle}</span>
              </div>
              <div className="flex flex-col gap-2">
                <label className="font-mono text-xs uppercase tracking-widest text-ink-soft">Your message</label>
                <textarea
                  value={messageText}
                  onChange={(e) => setMessageText(e.target.value)}
                  placeholder={`Hi ${landlord?.name?.split(" ")[0] ?? "there"}, I'm interested in this property…`}
                  rows={5}
                  className={`${inputCls} resize-none`}
                />
              </div>
              {error && <p className="text-sm text-red-600">{error}</p>}
            </div>
            <div className="px-6 pb-5 flex gap-3 justify-end">
              <button onClick={() => setModal(null)}
                className="inline-flex items-center justify-center font-semibold text-sm px-5 py-2 rounded-pill border border-mist text-forest hover:bg-forest hover:border-forest hover:text-white transition-colors">
                Cancel
              </button>
              <button
                onClick={submitMessage}
                disabled={!messageText.trim() || busy}
                className="inline-flex items-center justify-center gap-2 font-semibold text-sm px-5 py-2 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors disabled:opacity-40"
              >
                {busy ? <><Spinner size="sm" />Sending…</> : "Send message"}
              </button>
            </div>
          </div>
        </div>
      )}

      {toast && <Toast message={toast} onClose={() => setToast(null)} />}
    </>
  );
}
