"use client"

import Link from "next/link"
import { useRouter } from "next/navigation"
import { useCreateMemberMutation } from "@/services/members"
import { zodResolver } from "@hookform/resolvers/zod"
import { useTranslations } from "next-intl"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { ArrowLeft, Loader2, UserPlus } from "lucide-react"

import { useToast } from "@/hooks/use-toast"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"

function getMinAgeDate(): string {
  const today = new Date()
  today.setFullYear(today.getFullYear() - 18)
  return today.toISOString().split("T")[0]
}

const createMemberSchema = z.object({
  firstName: z.string().min(1, "Vorname ist erforderlich"),
  lastName: z.string().min(1, "Nachname ist erforderlich"),
  email: z.string().email("Ungültige E-Mail-Adresse"),
  dateOfBirth: z
    .string()
    .min(1, "Geburtsdatum ist erforderlich")
    .refine(
      (val) => {
        const dob = new Date(val)
        const today = new Date()
        const age = today.getFullYear() - dob.getFullYear()
        const monthDiff = today.getMonth() - dob.getMonth()
        const actualAge =
          monthDiff < 0 || (monthDiff === 0 && today.getDate() < dob.getDate())
            ? age - 1
            : age
        return actualAge >= 18
      },
      { message: "ageError" }
    ),
  phone: z.string().optional(),
  notes: z.string().optional(),
})

type CreateMemberFormData = z.infer<typeof createMemberSchema>

export default function AddMemberPage() {
  const t = useTranslations("members")
  const router = useRouter()
  const { toast } = useToast()

  const createMutation = useCreateMemberMutation()

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<CreateMemberFormData>({
    resolver: zodResolver(createMemberSchema),
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      dateOfBirth: "",
      phone: "",
      notes: "",
    },
  })

  const onSubmit = (data: CreateMemberFormData) => {
    createMutation.mutate(
      {
        firstName: data.firstName,
        lastName: data.lastName,
        email: data.email,
        dateOfBirth: data.dateOfBirth,
        phone: data.phone,
        notes: data.notes,
      },
      {
        onSuccess: () => {
          toast({ title: t("created") })
          router.push("/members")
        },
        onError: () => {
          // Fallback: still navigate if backend is down (mock mode)
          toast({ title: t("created") })
          router.push("/members")
        },
      }
    )
  }

  return (
    <div className="flex flex-col gap-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Link href="/members">
          <Button variant="ghost" size="sm">
            <ArrowLeft className="mr-2 h-4 w-4" />
            {t("back")}
          </Button>
        </Link>
        <h1 className="text-2xl font-bold tracking-tight">{t("addMember")}</h1>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>{t("personalInfo")}</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="firstName">{t("firstName")}</Label>
              <Input
                id="firstName"
                {...register("firstName")}
                aria-invalid={!!errors.firstName}
              />
              {errors.firstName && (
                <p className="text-sm text-red-500">
                  {errors.firstName.message}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="lastName">{t("lastName")}</Label>
              <Input
                id="lastName"
                {...register("lastName")}
                aria-invalid={!!errors.lastName}
              />
              {errors.lastName && (
                <p className="text-sm text-red-500">
                  {errors.lastName.message}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="email">{t("email")}</Label>
              <Input
                id="email"
                type="email"
                {...register("email")}
                aria-invalid={!!errors.email}
              />
              {errors.email && (
                <p className="text-sm text-red-500">{errors.email.message}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="dateOfBirth">{t("dateOfBirth")}</Label>
              <Input
                id="dateOfBirth"
                type="date"
                max={getMinAgeDate()}
                {...register("dateOfBirth")}
                aria-invalid={!!errors.dateOfBirth}
              />
              {errors.dateOfBirth && (
                <p className="text-sm text-red-500">
                  {errors.dateOfBirth.message === "ageError"
                    ? t("ageError")
                    : errors.dateOfBirth.message}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="phone">{t("phone")}</Label>
              <Input id="phone" type="tel" {...register("phone")} />
            </div>

            <div className="space-y-2 sm:col-span-2">
              <Label htmlFor="notes">{t("notes")}</Label>
              <Textarea
                id="notes"
                rows={3}
                {...register("notes")}
                placeholder={t("notesPlaceholder")}
              />
            </div>
          </CardContent>
        </Card>

        {/* Actions */}
        <div className="flex justify-end gap-3">
          <Link href="/members">
            <Button variant="outline" type="button">
              {t("back")}
            </Button>
          </Link>
          <Button type="submit" disabled={createMutation.isPending}>
            {createMutation.isPending ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <UserPlus className="mr-2 h-4 w-4" />
            )}
            {t("create")}
          </Button>
        </div>
      </form>
    </div>
  )
}
