"use client";

import { useRef, useState } from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { Camera, KeyRound } from "lucide-react";
import { PageHeader, Breadcrumbs } from "@/components/shared/page-header";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FormField } from "@/components/ui/form-field";
import { Avatar } from "@/components/shared/avatar";
import { useT } from "@/i18n";
import { useSession } from "@/features/auth/session";
import { updateProfile, changePhoto, changePassword } from "@/services/profile";
import { applyFieldErrors, friendlyErrorMessage } from "@/lib/errors";
import { formatDate } from "@/lib/format";
import { useI18n } from "@/i18n";

const profileSchema = z.object({
  name: z.string().min(1, "errors.required"),
  email: z.string().email("errors.email"),
  phone: z.string().optional(),
  date_of_birth: z.string().optional(),
});

const passwordSchema = z
  .object({
    current_password: z.string().min(1, "errors.required"),
    password: z.string().min(8, "errors.generic"),
    password_confirmation: z.string().min(1, "errors.required"),
  })
  .refine((values) => values.password === values.password_confirmation, {
    path: ["password_confirmation"],
    message: "errors.passwordMismatch",
  });

type ProfileValues = z.infer<typeof profileSchema>;
type PasswordValues = z.infer<typeof passwordSchema>;

export default function SettingsPage() {
  const t = useT();
  const { locale } = useI18n();
  const { admin, setAdmin } = useSession();
  const photoInputRef = useRef<HTMLInputElement>(null);
  const [photoBusy, setPhotoBusy] = useState(false);

  const profileForm = useForm<ProfileValues>({
    resolver: zodResolver(profileSchema),
    mode: "onTouched",
    values: {
      name: admin?.name ?? "",
      email: admin?.email ?? "",
      phone: admin?.phone ?? "",
      date_of_birth: admin?.date_of_birth ?? "",
    },
  });

  const passwordForm = useForm<PasswordValues>({
    resolver: zodResolver(passwordSchema),
    mode: "onTouched",
    defaultValues: { current_password: "", password: "", password_confirmation: "" },
  });

  async function onSubmitProfile(values: ProfileValues) {
    try {
      const response = await updateProfile(values);
      toast.success(response.Message || t("common.save"));
      if (response.Model) setAdmin(response.Model);
    } catch (error) {
      const shown = applyFieldErrors(
        error,
        (field, message) => profileForm.setError(field as never, { message }),
        { only: ["name", "email", "phone", "date_of_birth"] },
      );
      if (shown === 0) toast.error(friendlyErrorMessage(error, t));
    }
  }

  async function onSubmitPassword(values: PasswordValues) {
    try {
      const response = await changePassword(values);
      toast.success(response.Message || t("settings.passwordSuccess"));
      passwordForm.reset();
    } catch (error) {
      // "The current password is wrong" belongs under the current-password box, which is the one
      // field the operator can do anything about.
      const shown = applyFieldErrors(
        error,
        (field, message) => passwordForm.setError(field as never, { message }),
        { only: ["current_password", "password", "password_confirmation"] },
      );
      if (shown === 0) toast.error(friendlyErrorMessage(error, t));
    }
  }

  async function handlePhoto(file: File | null) {
    if (!file) return;
    setPhotoBusy(true);
    try {
      const response = await changePhoto(file);
      toast.success(response.Message || t("settings.photoSuccess"));
      if (response.Model) setAdmin(response.Model);
    } catch (error) {
      toast.error(friendlyErrorMessage(error, t));
    } finally {
      setPhotoBusy(false);
    }
  }

  return (
    <div className="mx-auto max-w-4xl">
      <Breadcrumbs items={[{ label: t("nav.settings"), href: "/settings" }, { label: t("settings.profileTitle") }]} />
      <PageHeader title={t("settings.title")} subtitle={t("settings.subtitle")} />

      <Card>
        <CardHeader>
          <CardTitle>{t("settings.profileTitle")}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="mb-6 flex items-center gap-4">
            <label htmlFor="photo-upload" className="relative cursor-pointer">
              <Avatar src={admin?.photo} name={admin?.name} size="lg" />
              <span className="absolute -bottom-1 -end-1 flex h-7 w-7 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-sm">
                {photoBusy ? (
                  <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-t-transparent" />
                ) : (
                  <Camera className="h-3.5 w-3.5" aria-hidden />
                )}
              </span>
              <input
                id="photo-upload"
                ref={photoInputRef}
                type="file"
                accept="image/*"
                className="sr-only"
                onChange={(event) => handlePhoto(event.target.files?.[0] ?? null)}
                disabled={photoBusy}
              />
            </label>
            <div>
              <p className="font-semibold text-foreground">{admin?.name}</p>
              <p className="text-xs text-muted-foreground">{t("settings.photoSuccess")}</p>
            </div>
          </div>

          <form onSubmit={profileForm.handleSubmit(onSubmitProfile)} className="grid gap-4 sm:grid-cols-2" noValidate>
            <FormField label={t("drivers.fieldName")} htmlFor="profile-name" required error={profileForm.formState.errors.name?.message}>
              <Input id="profile-name" {...profileForm.register("name")} />
            </FormField>
            <FormField label={t("auth.email")} htmlFor="profile-email" required error={profileForm.formState.errors.email?.message}>
              <Input id="profile-email" type="email" dir="ltr" {...profileForm.register("email")} />
            </FormField>
            <FormField label={t("drivers.fieldPhone")} htmlFor="profile-phone" error={profileForm.formState.errors.phone?.message}>
              <Input id="profile-phone" dir="ltr" {...profileForm.register("phone")} />
            </FormField>
            <FormField
              label={t("drivers.fieldDateOfBirth")}
              htmlFor="profile-dob"
              hint={admin?.date_of_birth ? formatDate(admin.date_of_birth, locale) : undefined}
              error={profileForm.formState.errors.date_of_birth?.message}
            >
              <Input id="profile-dob" type="date" dir="ltr" {...profileForm.register("date_of_birth")} />
            </FormField>
            <div className="sm:col-span-2 flex justify-end">
              <Button type="submit" loading={profileForm.formState.isSubmitting}>
                {t("common.save")}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>

      <Card className="mt-6">
        <CardHeader>
          <CardTitle>{t("settings.securityTitle")}</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={passwordForm.handleSubmit(onSubmitPassword)} className="grid gap-4 sm:grid-cols-2" noValidate>
            <FormField label={t("auth.currentPassword")} htmlFor="current_password" required error={passwordForm.formState.errors.current_password?.message}>
              <Input id="current_password" type="password" autoComplete="current-password" {...passwordForm.register("current_password")} />
            </FormField>
            <div />
            <FormField label={t("auth.newPassword")} htmlFor="new_password" required error={passwordForm.formState.errors.password?.message}>
              <Input id="new_password" type="password" autoComplete="new-password" {...passwordForm.register("password")} />
            </FormField>
            <FormField label={t("auth.confirmPassword")} htmlFor="confirm_password" required error={passwordForm.formState.errors.password_confirmation?.message}>
              <Input id="confirm_password" type="password" autoComplete="new-password" {...passwordForm.register("password_confirmation")} />
            </FormField>
            <div className="sm:col-span-2 flex justify-end">
              <Button type="submit" variant="outline" loading={passwordForm.formState.isSubmitting}>
                <KeyRound className="h-4 w-4" aria-hidden />
                {t("settings.securityTitle")}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}