import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import { updateSubscribed, sendBulkEmail } from './actions';

const SOURCE_LABELS: Record<string, string> = {
  CUSTOMER: 'Account',
  NEWSLETTER: 'Newsletter',
  GUEST: 'Guest order',
};

export default async function CustomersPage({
  searchParams,
}: {
  searchParams: { sent?: string; failed?: string };
}) {
  let entries = [];
  try {
    entries = await prisma.mailingListEntry.findMany();
    entries.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
  } catch (err) {
    console.error('Error fetching mailing list:', err);
  }
  const subscribedCount = entries.filter((e) => e.subscribed).length;

  return (
    <div className="mx-auto max-w-3xl px-6 py-12">
      <AdminNav />
      <h1 className="font-display text-3xl">Email customers</h1>
      <p className="mt-2 text-sm text-muted">
        Everyone who&apos;s made an account, signed up for the newsletter, or checked out as a
        guest, in one list. Untick Subscribed to leave someone out of future mailings.
      </p>

      {searchParams.sent !== undefined && (
        <div className="mt-6 border border-splash-blue bg-splash-blue/5 p-4 text-sm">
          Sent to {searchParams.sent} recipient{searchParams.sent === '1' ? '' : 's'}.
          {Number(searchParams.failed) > 0 && ` ${searchParams.failed} failed to send.`}
        </div>
      )}

      <h2 className="tag-label mt-10 mb-3 text-ink">
        Mailing list ({subscribedCount} of {entries.length} subscribed)
      </h2>
      {entries.length === 0 ? (
        <p className="text-sm text-muted">No one on the list yet.</p>
      ) : (
        <div className="divide-y divide-line border-t border-line">
          {entries.map((e) => (
            <div key={e.id} className="flex items-center gap-4 py-3">
              <div className="flex-1">
                <p className="font-medium">{e.name || e.email}</p>
                {e.name && <p className="text-xs text-muted">{e.email}</p>}
              </div>
              <span className="tag-label text-muted">{SOURCE_LABELS[e.source] ?? e.source}</span>
              <form action={updateSubscribed} className="flex items-center gap-2">
                <input type="hidden" name="id" value={e.id} />
                <label className="flex items-center gap-1.5 text-xs text-muted">
                  <input
                    type="checkbox"
                    name="subscribed"
                    value="1"
                    defaultChecked={e.subscribed}
                    className="h-3.5 w-3.5 accent-clay"
                  />
                  Subscribed
                </label>
                <button type="submit" className="tag-label hover:text-clay">
                  Save
                </button>
              </form>
            </div>
          ))}
        </div>
      )}

      <h2 className="tag-label mt-10 mb-3 text-ink">Send an email</h2>
      <form action={sendBulkEmail} className="space-y-6">
        <div>
          <label htmlFor="subject" className="tag-label mb-2 block">
            Subject
          </label>
          <input
            id="subject"
            name="subject"
            required
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
            placeholder="What's new at Craft2Prints"
          />
        </div>
        <div>
          <label htmlFor="message" className="tag-label mb-2 block">
            Message
          </label>
          <textarea
            id="message"
            name="message"
            required
            rows={8}
            className="w-full border border-line bg-paper px-3 py-2 text-sm"
            placeholder="Write your message here…"
          />
        </div>
        <div>
          <label htmlFor="attachment" className="tag-label mb-2 block">
            Attachment (optional)
          </label>
          <input id="attachment" name="attachment" type="file" className="w-full text-sm" />
        </div>
        <button type="submit" className="bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark">
          Send to {subscribedCount} subscribed recipient{subscribedCount === 1 ? '' : 's'}
        </button>
      </form>
    </div>
  );
}
