"use client";

import { useActionState, useEffect } from "react";
import { createClient, updateClient } from "@/lib/actions/clients";

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

export function ClientModal({
  isOpen,
  onClose,
  mode = "create",
  clientId,
  defaultName,
  defaultEmail,
}: ClientModalProps) {
  const boundAction =
    mode === "edit" && clientId
      ? updateClient.bind(null, clientId)
      : createClient;

  const [state, formAction, pending] = useActionState(boundAction, null);

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

  if (!isOpen) return null;

  const title = mode === "edit" ? "Edit Client" : "Add Client";

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white rounded-xl shadow-xl p-6 w-full max-w-md">
        <h2 className="text-[var(--navy)] text-lg font-semibold mb-4">
          {title}
        </h2>
        <form action={formAction} className="space-y-4">
          <div>
            <label
              htmlFor="name"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              Name
            </label>
            <input
              id="name"
              name="name"
              type="text"
              defaultValue={defaultName}
              required
              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--gold)]"
            />
          </div>
          <div>
            <label
              htmlFor="email"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              Email
            </label>
            <input
              id="email"
              name="email"
              type="email"
              defaultValue={defaultEmail}
              required
              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--gold)]"
            />
          </div>
          {state?.error && (
            <p className="text-red-500 text-sm">{state.error}</p>
          )}
          <div className="flex justify-end gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm text-gray-600 border border-gray-200 rounded-lg hover:bg-gray-50"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={pending}
              className="px-4 py-2 text-sm text-white bg-[var(--gold)] rounded-lg hover:opacity-90 disabled:opacity-50"
            >
              {pending ? "Saving..." : "Save"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
