"use client";

import { useActionState, useEffect, useState } from "react";
import { createClient, updateClient } from "@/lib/actions/clients";
import type { ClientContact } from "@/lib/db/schema";

type ClientModalProps = {
  isOpen: boolean;
  onClose: () => void;
  mode?: "create" | "edit";
  clientId?: string;
  defaultName?: string;
  defaultEmail?: string;
  defaultPropertyAddress?: string;
  defaultContacts?: ClientContact[];
};

const inputCls = "block w-full rounded-lg border border-gray-300 px-3 py-2 text-sm text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:border-transparent transition";

export function ClientModal({
  isOpen, onClose, mode = "create", clientId,
  defaultName, defaultEmail, defaultPropertyAddress, defaultContacts,
}: ClientModalProps) {
  const boundAction = mode === "edit" && clientId ? updateClient.bind(null, clientId) : createClient;
  const [state, formAction, pending] = useActionState(boundAction, null);

  const [extraContacts, setExtraContacts] = useState<ClientContact[]>(defaultContacts ?? []);
  const [contactInput, setContactInput] = useState({ name: "", email: "" });
  const [contactError, setContactError] = useState<string | null>(null);

  useEffect(() => { if (state?.success) onClose(); }, [state, onClose]);

  useEffect(() => {
    setExtraContacts(defaultContacts ?? []);
    setContactInput({ name: "", email: "" });
    setContactError(null);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [clientId, isOpen]);

  function addContact() {
    const name = contactInput.name.trim();
    const email = contactInput.email.trim().toLowerCase();
    if (!name) { setContactError("Name is required"); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setContactError("Valid email required"); return; }
    if (extraContacts.some(c => c.email === email)) { setContactError("That email is already added"); return; }
    setExtraContacts(prev => [...prev, { name, email }]);
    setContactInput({ name: "", email: "" });
    setContactError(null);
  }

  if (!isOpen) return null;

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 50, display: "flex", alignItems: "center", justifyContent: "center", backgroundColor: "rgba(0,0,0,0.4)", padding: "1rem" }}>
      <div style={{ backgroundColor: "white", borderRadius: "1rem", boxShadow: "0 8px 32px rgba(0,0,0,0.18)", padding: "2rem", width: "100%", maxWidth: "32rem", maxHeight: "90vh", overflowY: "auto" }}>
        <h2 style={{ color: "#1B2B4B", fontSize: "1.125rem", fontWeight: 700, marginBottom: "1.25rem" }}>
          {mode === "edit" ? "Edit Client" : "Add Client"}
        </h2>
        <form action={formAction} style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>

          {/* Primary contact */}
          <div style={{ padding: "1rem", border: "1px solid #E5E7EB", borderRadius: "0.5rem", backgroundColor: "#F9FAFB" }}>
            <p style={{ fontSize: "0.75rem", fontWeight: 600, color: "#6B7280", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "0.75rem" }}>Primary Contact</p>
            <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
              <div>
                <label htmlFor="name" style={{ display: "block", fontSize: "0.875rem", fontWeight: 500, color: "#1B2B4B", marginBottom: "0.25rem" }}>Name</label>
                <input id="name" name="name" type="text" defaultValue={defaultName} required className={inputCls} placeholder="Jane Smith" />
              </div>
              <div>
                <label htmlFor="email" style={{ display: "block", fontSize: "0.875rem", fontWeight: 500, color: "#1B2B4B", marginBottom: "0.25rem" }}>Email</label>
                <input id="email" name="email" type="email" defaultValue={defaultEmail} required className={inputCls} placeholder="jane@example.com" />
              </div>
            </div>
          </div>

          {/* Additional people */}
          <div>
            <p style={{ fontSize: "0.75rem", fontWeight: 600, color: "#6B7280", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: "0.5rem" }}>
              Additional People <span style={{ fontWeight: 400, textTransform: "none" }}>(co-buyer, spouse, partner…)</span>
            </p>

            {extraContacts.length > 0 && (
              <div style={{ display: "flex", flexDirection: "column", gap: "0.375rem", marginBottom: "0.75rem" }}>
                {extraContacts.map(c => (
                  <div key={c.email} style={{ display: "flex", alignItems: "center", gap: "0.5rem", padding: "0.5rem 0.75rem", backgroundColor: "#F0F9FF", border: "1px solid #BAE6FD", borderRadius: "0.375rem" }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <p style={{ fontSize: "0.875rem", fontWeight: 500, color: "#1B2B4B", margin: 0 }}>{c.name}</p>
                      <p style={{ fontSize: "0.75rem", color: "#6B7280", margin: 0 }}>{c.email}</p>
                    </div>
                    <button type="button" onClick={() => setExtraContacts(p => p.filter(x => x.email !== c.email))}
                      aria-label={`Remove ${c.name}`}
                      style={{ background: "none", border: "none", cursor: "pointer", color: "#9CA3AF", fontSize: "1.125rem", lineHeight: 1, padding: "0.25rem" }}>
                      &#xd7;
                    </button>
                  </div>
                ))}
              </div>
            )}

            <div style={{ padding: "0.75rem", border: "1px dashed #D1D5DB", borderRadius: "0.5rem", display: "flex", flexDirection: "column", gap: "0.5rem" }}>
              <div style={{ display: "flex", gap: "0.5rem" }}>
                <input type="text" value={contactInput.name}
                  onChange={e => { setContactInput(p => ({ ...p, name: e.target.value })); setContactError(null); }}
                  placeholder="Name" className={inputCls} style={{ flex: 1 }} />
                <input type="email" value={contactInput.email}
                  onChange={e => { setContactInput(p => ({ ...p, email: e.target.value })); setContactError(null); }}
                  onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addContact(); } }}
                  placeholder="Email" className={inputCls} style={{ flex: 1 }} />
                <button type="button" onClick={addContact}
                  style={{ padding: "0.5rem 0.875rem", backgroundColor: "#1B2B4B", color: "white", borderRadius: "0.375rem", border: "none", fontSize: "0.875rem", fontWeight: 500, cursor: "pointer", whiteSpace: "nowrap" }}>
                  Add
                </button>
              </div>
              {contactError && <p style={{ fontSize: "0.75rem", color: "#DC2626", margin: 0 }}>{contactError}</p>}
            </div>
          </div>

          {/* Property address */}
          <div>
            <label htmlFor="propertyAddress" style={{ display: "block", fontSize: "0.875rem", fontWeight: 500, color: "#1B2B4B", marginBottom: "0.25rem" }}>Property Address</label>
            <input id="propertyAddress" name="propertyAddress" type="text" defaultValue={defaultPropertyAddress} className={inputCls} placeholder="123 Main St, Salt Lake City, UT 84101" />
          </div>

          {/* Serialize extra contacts as hidden field */}
          <input type="hidden" name="contacts" value={JSON.stringify(extraContacts)} />

          {state?.error && <p style={{ color: "#DC2626", fontSize: "0.875rem" }}>{state.error}</p>}
          <div style={{ display: "flex", justifyContent: "flex-end", gap: "0.75rem", paddingTop: "0.5rem" }}>
            <button type="button" onClick={onClose} className="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition">Cancel</button>
            <button type="submit" disabled={pending} className="px-4 py-2 text-sm font-semibold text-white rounded-lg transition hover:brightness-110 disabled:opacity-50" style={{ backgroundColor: "#C9A84C" }}>
              {pending ? "Saving..." : "Save"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
