import Link from "next/link";
import { XCircle } from "lucide-react";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { verifyResetToken } from "@/lib/appwrite/password-reset-actions";
import { ResetPasswordForm } from "./components/reset-password-form";

interface Props {
  searchParams: Promise<{ token?: string }>;
}

export default async function ResetPasswordPage({ searchParams }: Props) {
  const { token } = await searchParams;

  if (!token) {
    return <InvalidToken message="Geçersiz bağlantı. Yeni bir sıfırlama kodu talep edin." />;
  }

  const { valid } = await verifyResetToken(token);

  if (!valid) {
    return <InvalidToken message="Bu kod geçersiz veya süresi dolmuş. Yeni bir sıfırlama kodu talep edin." />;
  }

  return (
    <div className="flex min-h-svh items-center justify-center p-6">
      <div className="w-full max-w-sm">
        <ResetPasswordForm token={token} />
      </div>
    </div>
  );
}

function InvalidToken({ message }: { message: string }) {
  return (
    <div className="flex min-h-svh items-center justify-center p-6">
      <div className="w-full max-w-sm">
        <Card>
          <CardHeader className="text-center">
            <div className="text-destructive mx-auto mb-2 flex size-12 items-center justify-center rounded-full bg-red-50">
              <XCircle className="size-6" />
            </div>
            <CardTitle className="text-xl">Geçersiz kod</CardTitle>
          </CardHeader>
          <CardContent className="flex flex-col items-center gap-4 text-center">
            <p className="text-muted-foreground text-sm">{message}</p>
            <Link
              href="/forgot-password"
              className="text-primary text-sm underline underline-offset-4"
            >
              Yeni kod talep et
            </Link>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
