import { Card } from "@/components/ui/card";
import { FormSubmitButton } from "@/components/ui/form-submit-button";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { env } from "@/lib/env";
import { createClient } from "@/lib/supabase/server";
import { ROLES } from "@/lib/constants";
import { REGION_DEFINITIONS } from "@/lib/regions";
import { createUserAction, updateUserAccessAction } from "@/app/(app)/admin/users/actions";

type ProfileRow = {
  id: string;
  email: string;
  role: "admin" | "affiliate";
  created_at: string;
};

type CountryRow = {
  id: number;
  code: string;
  name: string;
};

type AccessRow = {
  user_id: string;
  country_id: number;
};

export default async function AdminUsersPage() {
  if (!env.hasSupabasePublicEnv) {
    return (
      <Card>
        <h2 className="text-lg font-semibold text-slate-900">VAE User Access</h2>
        <p className="mt-2 text-sm text-amber-700">
          Configure real Supabase environment values to enable user management.
        </p>
      </Card>
    );
  }

  const supabase = await createClient();

  const [profilesRes, countriesRes, accessRes] = await Promise.all([
    supabase
      .from("profiles")
      .select("id, email, role, created_at")
      .order("created_at", { ascending: false }),
    supabase.from("countries").select("id, code, name").order("code", { ascending: true }),
    supabase.from("user_country_access").select("user_id, country_id"),
  ]);

  if (profilesRes.error) throw new Error(profilesRes.error.message);
  if (countriesRes.error) throw new Error(countriesRes.error.message);
  if (accessRes.error) throw new Error(accessRes.error.message);

  const profiles = (profilesRes.data ?? []) as ProfileRow[];
  const countries = (countriesRes.data ?? []) as CountryRow[];
  const accessRows = (accessRes.data ?? []) as AccessRow[];

  const accessByUser = new Map<string, Set<number>>();
  for (const row of accessRows) {
    const set = accessByUser.get(row.user_id) ?? new Set<number>();
    set.add(row.country_id);
    accessByUser.set(row.user_id, set);
  }

  return (
    <div className="space-y-4">
      <Card>
        <h2 className="text-lg font-semibold text-slate-900">VAE User Access</h2>
        <p className="mt-2 text-sm text-slate-600">
          Create users, assign roles, and control country access for Otsuka affiliate dashboards and uploads.
        </p>
        <p className="mt-2 text-sm text-amber-700">
          Affiliate users must be scoped to one dashboard region only.
        </p>
        <div className="mt-3 flex flex-wrap gap-2">
          {Object.entries(REGION_DEFINITIONS).map(([region, countries]) => (
            <span
              key={region}
              className="caption rounded-full border border-[#d7e4f3] bg-[#f7fbff] px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-[#2663AC]"
            >
              {region === "OPEL" ? region : `${region}: ${countries.join(", ")}`}
            </span>
          ))}
        </div>
      </Card>

      <Card>
        <h3 className="text-sm font-semibold text-slate-900">Create New VAE User</h3>
        <form action={createUserAction} className="mt-4 space-y-3">
          <div className="grid gap-3 md:grid-cols-3">
            <Input name="email" type="email" placeholder="email@company.com" required />
            <Input name="password" type="password" placeholder="Temporary password" required />
            <Select name="role" defaultValue={ROLES.affiliate}>
              <option value={ROLES.affiliate}>affiliate</option>
              <option value={ROLES.admin}>admin</option>
            </Select>
          </div>
          <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
            {countries.map((country) => (
              <label key={country.id} className="flex items-center gap-2 text-sm text-slate-600">
                <input type="checkbox" name="country_ids" value={country.id} className="rounded" />
                {country.code} - {country.name}
              </label>
            ))}
          </div>
          <FormSubmitButton idleLabel="Create User" pendingLabel="Creating..." />
        </form>
      </Card>

      <div className="space-y-3">
        {profiles.map((profile) => {
          const assigned = accessByUser.get(profile.id) ?? new Set<number>();
          return (
            <Card key={profile.id}>
              <div className="flex flex-wrap items-center justify-between gap-2">
                <div>
                  <p className="text-sm font-medium text-slate-900">{profile.email}</p>
                  <p className="caption text-xs text-slate-500">
                    {profile.id} · Created {new Date(profile.created_at).toLocaleDateString("en-GB")}
                  </p>
                </div>
              </div>

              <form action={updateUserAccessAction} className="mt-4 space-y-3">
                <input type="hidden" name="user_id" value={profile.id} />
                <div className="max-w-[240px]">
                  <label className="caption text-xs uppercase tracking-[0.16em] text-slate-500">
                    Role
                  </label>
                  <Select name="role" defaultValue={profile.role}>
                    <option value={ROLES.affiliate}>affiliate</option>
                    <option value={ROLES.admin}>admin</option>
                  </Select>
                </div>
                <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
                  {countries.map((country) => (
                    <label key={country.id} className="flex items-center gap-2 text-sm text-slate-600">
                      <input
                        type="checkbox"
                        name="country_ids"
                        value={country.id}
                        defaultChecked={assigned.has(country.id)}
                        className="rounded"
                      />
                      {country.code} - {country.name}
                    </label>
                  ))}
                </div>
                <FormSubmitButton
                  idleLabel="Save Access"
                  pendingLabel="Saving..."
                  variant="secondary"
                />
              </form>
            </Card>
          );
        })}
      </div>
    </div>
  );
}
