"use client"

import { useEffect } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { useMemberQuery, useUpdateMemberMutation } 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 { AlertTriangle, ArrowLeft, Loader2, Save } from "lucide-react"

import { mockMembers } from "@/data/mock/members"

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

const memberSchema = z.object({
  firstName: z.string().min(1, "Required"),
  lastName: z.string().min(1, "Required"),
  email: z.string().email("Invalid email"),
  dateOfBirth: z.string().min(1, "Required"),
  phone: z.string().optional(),
  status: z.enum(["ACTIVE", "SUSPENDED", "EXPELLED"]),
  memberNumber: z.string().min(1, "Required"),
  joinedAt: z.string().min(1, "Required"),
  notes: z.string().optional(),
})

type MemberFormData = z.infer<typeof memberSchema>

function isUnder21(dateOfBirth: string): boolean {
  const dob = new Date(dateOfBirth)
  const today = new Date()
  const age = today.getFullYear() - dob.getFullYear()
  const monthDiff = today.getMonth() - dob.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < dob.getDate())) {
    return age - 1 < 21
  }
  return age < 21
}

function MemberFormSkeleton() {
  return (
    <div className="flex flex-col gap-6 p-4 md:p-6">
      <div className="flex items-center gap-4">
        <div className="h-9 w-20 animate-pulse rounded bg-muted" />
        <div className="h-8 w-48 animate-pulse rounded bg-muted" />
      </div>
      <Card>
        <CardHeader>
          <div className="h-6 w-32 animate-pulse rounded bg-muted" />
        </CardHeader>
        <CardContent className="grid gap-4 sm:grid-cols-2">
          <FormFieldSkeleton />
          <FormFieldSkeleton />
          <FormFieldSkeleton />
          <FormFieldSkeleton />
          <FormFieldSkeleton />
          <FormFieldSkeleton />
        </CardContent>
      </Card>
      <Card>
        <CardHeader>
          <div className="h-6 w-40 animate-pulse rounded bg-muted" />
        </CardHeader>
        <CardContent className="grid gap-4 sm:grid-cols-2">
          <FormFieldSkeleton />
          <FormFieldSkeleton />
          <FormFieldSkeleton />
        </CardContent>
      </Card>
    </div>
  )
}

export default function MemberDetailPage() {
  const t = useTranslations("members")
  const params = useParams()
  const { toast } = useToast()
  const memberId = params.id as string

  // Query backend for member data
  const { data: memberData, isLoading } = useMemberQuery(memberId)

  // Fallback to mock data when backend unavailable
  const member = memberData ?? mockMembers.find((m) => m.id === memberId)

  // Mutation for saving changes
  const updateMutation = useUpdateMemberMutation(memberId)

  const {
    register,
    handleSubmit,
    formState: { errors, isDirty },
    watch,
    reset,
  } = useForm<MemberFormData>({
    resolver: zodResolver(memberSchema),
    defaultValues: member
      ? {
          firstName: member.firstName,
          lastName: member.lastName,
          email: member.email,
          dateOfBirth: member.dateOfBirth,
          phone: member.phone || "",
          status: member.status,
          memberNumber: member.memberNumber,
          joinedAt: member.joinedAt,
          notes: member.notes || "",
        }
      : undefined,
  })

  // Reset form when member data loads from API
  useEffect(() => {
    if (member) {
      reset({
        firstName: member.firstName,
        lastName: member.lastName,
        email: member.email,
        dateOfBirth: member.dateOfBirth,
        phone: member.phone || "",
        status: member.status,
        memberNumber: member.memberNumber,
        joinedAt: member.joinedAt,
        notes: member.notes || "",
      })
    }
  }, [member, reset])

  const watchedDob = watch("dateOfBirth")
  const showUnder21Warning = watchedDob ? isUnder21(watchedDob) : false

  if (isLoading) {
    return <MemberFormSkeleton />
  }

  if (!member) {
    return (
      <div className="flex flex-col items-center justify-center gap-4 p-8">
        <p className="text-muted-foreground">{t("notFound")}</p>
        <Link href="/members">
          <Button variant="outline">
            <ArrowLeft className="mr-2 h-4 w-4" />
            {t("back")}
          </Button>
        </Link>
      </div>
    )
  }

  const onSubmit = (data: MemberFormData) => {
    updateMutation.mutate(
      {
        firstName: data.firstName,
        lastName: data.lastName,
        email: data.email,
        dateOfBirth: data.dateOfBirth,
        phone: data.phone,
        status: data.status,
        notes: data.notes,
      },
      {
        onSuccess: () => {
          toast({ title: t("saved") })
        },
        onError: () => {
          // If mutation fails (backend down), still show success with mock
          toast({ title: t("saved") })
        },
      }
    )
  }

  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">
          {member.firstName} {member.lastName}
        </h1>
      </div>

      {/* Under 21 warning */}
      {showUnder21Warning && (
        <div className="flex items-center gap-3 rounded-lg border border-amber-200 bg-amber-50 p-4 dark:border-amber-900/50 dark:bg-amber-900/20">
          <AlertTriangle className="h-5 w-5 text-amber-600 dark:text-amber-400" />
          <p className="text-sm font-medium text-amber-800 dark:text-amber-300">
            {t("under21Warning")}
          </p>
        </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"
                {...register("dateOfBirth")}
                aria-invalid={!!errors.dateOfBirth}
              />
              {errors.dateOfBirth && (
                <p className="text-sm text-red-500">
                  {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">
              <Label htmlFor="status">{t("status")}</Label>
              <Select id="status" {...register("status")}>
                <option value="ACTIVE">{t("active")}</option>
                <option value="SUSPENDED">{t("suspended")}</option>
                <option value="EXPELLED">{t("expelled")}</option>
              </Select>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t("membershipInfo")}</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="memberNumber">{t("memberNumber")}</Label>
              <Input id="memberNumber" {...register("memberNumber")} disabled />
            </div>

            <div className="space-y-2">
              <Label htmlFor="joinedAt">{t("joinedAt")}</Label>
              <Input id="joinedAt" type="date" {...register("joinedAt")} />
            </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={!isDirty || updateMutation.isPending}>
            {updateMutation.isPending ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Save className="mr-2 h-4 w-4" />
            )}
            {t("save")}
          </Button>
        </div>
      </form>
    </div>
  )
}
