import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import { ExternalLink } from "lucide-react";
import { InstanceActions } from "@/components/dashboard/instance-actions";
import { InstanceCredentials } from "@/components/dashboard/instance-credentials";
import { NewInstanceForm } from "@/components/dashboard/new-instance-form";
import { AgentConfigPanel } from "@/components/dashboard/agent-config-panel";
import { Badge, Card } from "@/components/ui";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { formatDate, instanceLimit, instancePublicUrl } from "@/lib/utils";

export default async function InstancesPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) redirect("/login");

  const user = await prisma.user.findUnique({
    where: { id: parseInt(session.user.id) },
    include: { instances: { orderBy: { created_at: "desc" } } }
  });
  const limit = instanceLimit(user?.subscription_tier);
  const instances = user?.instances || [];
  const hermesInstances = instances.filter((instance) => instance.app_type === "hermes");

  return (
    <div className="grid gap-6 xl:grid-cols-[360px_1fr]">
      <Card>
        <h1 className="text-2xl font-bold text-ink">Create Wakel AI</h1>
        <p className="mt-2 text-sm leading-6 text-slate-600">
          Deploy a real Docker runtime and attach a subdomain.
        </p>
        <div className="mt-6">
          <NewInstanceForm />
        </div>
        <p className="mt-4 text-xs text-slate-500">
          Wakel AI usage: {hermesInstances.length}/{limit}
        </p>
      </Card>

      <Card>
        <div className="flex items-center justify-between">
          <h2 className="text-xl font-bold text-ink">Wakel AI Instances</h2>
          <Badge>{user?.subscription_tier || "FREE"}</Badge>
        </div>
        <div className="mt-4 grid gap-3">
          {hermesInstances.length ? (
            hermesInstances.map((instance) => (
              <div key={instance.id} className="rounded-lg border border-slate-200 p-4">
                <div className="flex flex-col justify-between gap-4 lg:flex-row lg:items-start">
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="font-bold text-ink">{instance.name}</h3>
                      <Badge tone={instance.status === "RUNNING" ? "green" : instance.status === "ERROR" ? "red" : "amber"}>
                        {instance.status}
                      </Badge>
                    </div>
                    {instance.deployment_mode === "profile" ? (
                      <a className="mt-2 inline-flex items-center gap-1 text-sm font-medium text-brand" href="/dashboard/company">
                        موظف في شركتك · افتح لوحة الشركة
                        <ExternalLink size={14} />
                      </a>
                    ) : (
                      <a className="mt-2 inline-flex items-center gap-1 text-sm font-medium text-brand" href={instancePublicUrl(instance.subdomain)} target="_blank">
                        {instance.subdomain}
                        <ExternalLink size={14} />
                      </a>
                    )}
                    <p className="mt-2 text-xs text-slate-500">Created {formatDate(instance.created_at)}</p>
                    {instance.last_error && <p className="mt-3 rounded-md bg-red-50 p-3 text-xs text-red-700">{instance.last_error}</p>}
                  </div>
                  <InstanceActions instance_id={instance.id} />
                </div>
                <InstanceCredentials instance_id={instance.id} />
                {instance.status === "RUNNING" && (
                  <AgentConfigPanel instanceId={instance.id} initialNotes={instance.notes} roleId={instance.agent_role_id} />
                )}
              </div>
            ))
          ) : (
            <p className="rounded-lg border border-dashed border-slate-300 p-8 text-center text-sm text-slate-500">
              Create your first Wakel AI instance to start.
            </p>
          )}
        </div>
      </Card>
    </div>
  );
}
