"use client";

import { useState, useEffect, useRef } from "react";
import { AdminButton } from "@/components/admin/design-system";

export default function PriceSheetModal({
  customerCount,
  defaultSubject,
  onConfirm,
  onClose,
}: {
  customerCount: number;
  defaultSubject: string;
  onConfirm: (subject: string, customNote: string) => void;
  onClose: () => void;
}) {
  const [subject, setSubject] = useState(defaultSubject);
  const [note, setNote] = useState("");
  const [sending, setSending] = useState(false);
  const dialogRef = useRef<HTMLDialogElement | null>(null);

  useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;
    if (!dialog.open) dialog.showModal();
    const onCancel = (e: Event) => {
      e.preventDefault();
      onClose();
    };
    dialog.addEventListener("cancel", onCancel);
    return () => {
      dialog.removeEventListener("cancel", onCancel);
    };
  }, [onClose]);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!subject.trim()) return;
    setSending(true);
    onConfirm(subject.trim(), note.trim());
  }

  return (
    <dialog
      ref={dialogRef}
      aria-label="Send price sheet"
      className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 px-4 m-0 max-w-none max-h-none w-full h-full backdrop:bg-black/40"
    >
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg border border-[var(--admin-border)]">
        <div className="px-6 py-4 border-b border-[var(--admin-border)] flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-[var(--admin-text-primary)]">Send Price Sheet</h2>
            <p className="text-sm text-[var(--admin-text-muted)]">
              {customerCount === 1 ? "1 customer" : `${customerCount} customers`}
            </p>
          </div>
          <button type="button" onClick={onClose} aria-label="Close send price sheet" className="text-[var(--admin-text-muted)] hover:text-[var(--admin-text-secondary)]">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className="px-6 py-5 space-y-4">
            <div>
              <label htmlFor="ws-price-subject" className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1.5">Subject</label>
              <input aria-label="Ws Price Subject"
                id="ws-price-subject"
                value={subject}
                onChange={e => setSubject(e.target.value)}
                required
                aria-required="true"
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]"
              />
            </div>
            <div>
              <label htmlFor="ws-price-note" className="block text-sm font-medium text-[var(--admin-text-secondary)] mb-1.5">
                Add a Note <span className="text-[var(--admin-text-muted)] font-normal">(optional)</span>
              </label>
              <textarea aria-label=". 'Check Out Our New Seasonal Items On Page 2. Place Your Order By Friday For Weekend Pickup.'"
                id="ws-price-note"
                value={note}
                onChange={e => setNote(e.target.value)}
                rows={4}
                placeholder="e.g. 'Check out our new seasonal items on page 2. Place your order by Friday for weekend pickup.'"
                className="w-full rounded-xl border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)] resize-none"
              />
              <p className="mt-1 text-xs text-[var(--admin-text-muted)]">
                This note will appear at the top of the email, above the product table.
              </p>
            </div>
          </div>

          <div className="px-6 py-4 border-t border-[var(--admin-border)] flex items-center justify-between bg-[var(--admin-bg-subtle)] rounded-b-2xl">
            <div className="text-sm text-[var(--admin-text-muted)]">
              {customerCount === 1 ? "1 customer" : `${customerCount} customers`} will receive this email.
            </div>
            <div className="flex gap-3">
              <AdminButton type="button" variant="secondary" onClick={onClose}>
                Cancel
              </AdminButton>
              <AdminButton type="submit" variant="primary" disabled={sending || !subject.trim()} isLoading={sending}>
                {sending ? "Sending..." : `Send to ${customerCount === 1 ? "1 Customer" : `${customerCount} Customers`}`}
              </AdminButton>
            </div>
          </div>
        </form>
      </div>
    </dialog>
  );
}
