"use client";

import {useState, useTransition} from "react";
import {createTenant} from "@/features/tenants/server/actions";
import {CheckCircle, Copy} from "lucide-react";

type CreatedInfo = {
  companyName: string;
  slug: string;
  adminEmail: string;
  adminPassword: string;
  dashboardUrl: string;
};

export default function NewTenantPage() {
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();
  const [created, setCreated] = useState<CreatedInfo | null>(null);
  const [copied, setCopied] = useState<string | null>(null);

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    setError(null);

    // Capture the credentials before submitting
    const info: CreatedInfo = {
      companyName: fd.get("name") as string,
      slug: fd.get("slug") as string,
      adminEmail: fd.get("adminEmail") as string,
      adminPassword: fd.get("adminPassword") as string,
      dashboardUrl: `/company/${fd.get("slug")}`
    };

    startTransition(async () => {
      const result = await createTenant(fd);
      if (!result.success) {
        setError(result.error ?? "Unknown error");
      } else {
        setCreated(info);
      }
    });
  }

  function copyText(text: string, key: string) {
    navigator.clipboard.writeText(text);
    setCopied(key);
    setTimeout(() => setCopied(null), 2000);
  }

  if (created) {
    return (
      <div className="mx-auto max-w-2xl space-y-6 p-6">
        <div className="rounded-2xl border border-green-200 bg-green-50 p-6 shadow-sm">
          <div className="flex items-start gap-3">
            <CheckCircle className="mt-0.5 h-6 w-6 shrink-0 text-green-600" />
            <div>
              <h2 className="text-lg font-bold text-green-900">Tenant Created Successfully!</h2>
              <p className="mt-1 text-sm text-green-700">The company account is ready. Save these credentials:</p>
            </div>
          </div>

          <div className="mt-6 space-y-3">
            {[
              {label: "Company Name", value: created.companyName, key: "name"},
              {label: "Slug", value: created.slug, key: "slug", mono: true},
              {label: "Dashboard URL", value: created.dashboardUrl, key: "url", mono: true},
              {label: "Admin Email", value: created.adminEmail, key: "email"},
              {label: "Admin Password", value: created.adminPassword, key: "pass", sensitive: true}
            ].map(({label, value, key, mono, sensitive}) => (
              <div key={key} className="flex items-center justify-between rounded-xl border border-green-200 bg-white px-4 py-3">
                <div>
                  <p className="text-xs font-medium text-slate-500">{label}</p>
                  <p className={`text-sm font-semibold text-slate-900 ${mono ? "font-mono" : ""} ${sensitive ? "tracking-wider" : ""}`}>
                    {value}
                  </p>
                </div>
                <button
                  onClick={() => copyText(value, key)}
                  className="flex items-center gap-1 rounded-lg border border-slate-200 px-2 py-1.5 text-xs text-slate-600 hover:bg-slate-50 transition"
                >
                  <Copy className="h-3 w-3" />
                  {copied === key ? "Copied!" : "Copy"}
                </button>
              </div>
            ))}
          </div>

          <div className="mt-6 flex gap-3">
            <a
              href={created.dashboardUrl}
              target="_blank"
              className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 transition"
            >
              Open Dashboard ↗
            </a>
            <a
              href="/super-admin/tenants"
              className="rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-50 transition"
            >
              Back to Tenants
            </a>
            <button
              onClick={() => setCreated(null)}
              className="rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-50 transition"
            >
              Create Another
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-2xl space-y-6 p-6">
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Create New Tenant</h1>
        <p className="mt-1 text-slate-500">Set up a new company on the platform</p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <section>
          <h2 className="mb-4 text-sm font-semibold text-slate-700 uppercase tracking-wide">Company Info</h2>
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2">
              <label className="mb-1 block text-sm font-medium text-slate-700">Company Name *</label>
              <input
                name="name"
                required
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
                placeholder="Acme Car Rental"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Slug *</label>
              <input
                name="slug"
                required
                pattern="[a-z0-9-]+"
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm font-mono outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
                placeholder="acme-car-rental"
              />
              <p className="mt-1 text-xs text-slate-400">Lowercase letters, numbers and hyphens only</p>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Email *</label>
              <input
                name="email"
                type="email"
                required
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
                placeholder="info@acme.com"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Phone</label>
              <input
                name="phone"
                type="tel"
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Country</label>
              <input
                name="country"
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
                placeholder="SA"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">City</label>
              <input
                name="city"
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Currency</label>
              <select
                name="currency"
                defaultValue="USD"
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              >
                <option value="USD">USD</option>
                <option value="EUR">EUR</option>
                <option value="SAR">SAR</option>
                <option value="AED">AED</option>
                <option value="TND">TND</option>
                <option value="MAD">MAD</option>
                <option value="EGP">EGP</option>
              </select>
            </div>
          </div>
        </section>

        <hr className="border-slate-100" />

        <section>
          <h2 className="mb-4 text-sm font-semibold text-slate-700 uppercase tracking-wide">Admin Account</h2>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">First Name *</label>
              <input
                name="adminFirstName"
                required
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Last Name *</label>
              <input
                name="adminLastName"
                required
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Admin Email *</label>
              <input
                name="adminEmail"
                type="email"
                required
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              />
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-slate-700">Password *</label>
              <input
                name="adminPassword"
                type="password"
                required
                minLength={8}
                className="h-10 w-full rounded-lg border border-slate-200 px-3 text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
              />
            </div>
          </div>
        </section>

        {error && (
          <div className="rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700">
            {error}
          </div>
        )}

        <div className="flex gap-3">
          <button
            type="submit"
            disabled={isPending}
            className="rounded-lg bg-violet-600 px-6 py-2.5 text-sm font-medium text-white hover:bg-violet-700 disabled:opacity-50 transition"
          >
            {isPending ? "Creating..." : "Create Tenant"}
          </button>
          <a
            href="/super-admin/tenants"
            className="rounded-lg border border-slate-200 px-6 py-2.5 text-sm font-medium text-slate-600 hover:bg-slate-50 transition"
          >
            Cancel
          </a>
        </div>
      </form>
    </div>
  );
}
