"use client"

import { useState } from "react"
import { useForm, useWatch } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { CheckCircle2Icon, Loader2Icon, ShieldCheckIcon, XCircleIcon } from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/src/components/ui/button"
import { Input } from "@/src/components/ui/input"
import { TimePicker } from "@/src/components/ui/time-picker"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/src/components/ui/form"
import PhoneInput from "@/src/components/ui/phone-input"
import { useUpdateProfileMutation, useRequestPhoneOtpMutation } from "@/src/state/auth"
import type { Restaurant } from "@/src/state/auth"
import { PhoneOtpDialog } from "./phone-otp-dialog"
import { extractErrorMessage } from "./utils"

const profileSchema = z.object({
  restaurantName: z.string().min(1, "Le nom du restaurant est requis"),
  businessName: z.string().optional(),
  phoneNumber: z
    .string()
    .regex(/^\+\d{8,15}$/, "Le numéro doit être au format E.164 (ex: +22676123456)"),
  description: z.string().optional(),
  deliveryFee: z.coerce.number().min(0, "Doit être positif ou zéro"),
  minimumOrder: z.coerce.number().min(0, "Doit être positif ou zéro"),
  openTime: z.string().optional(),
  closeTime: z.string().optional(),
})

type ProfileValues = z.infer<typeof profileSchema>

interface ProfileFormProps {
  profile: Restaurant
}

export function ProfileForm({ profile }: ProfileFormProps) {
  const [updateProfile, { isLoading: isSaving }] = useUpdateProfileMutation()
  const [requestPhoneOtp] = useRequestPhoneOtpMutation()
  const [phoneOtpOpen, setPhoneOtpOpen] = useState(false)
  const [pendingPhoneNumber, setPendingPhoneNumber] = useState("")

  const form = useForm<ProfileValues>({
    resolver: zodResolver(profileSchema),
    values: {
      restaurantName: profile.restaurantName ?? "",
      businessName: profile.businessName ?? "",
      phoneNumber: profile.phoneNumber ?? "",
      description: profile.description ?? "",
      deliveryFee: profile.deliveryFee ?? 0,
      minimumOrder: profile.minimumOrder ?? 0,
      openTime: profile.openTime ?? "",
      closeTime: profile.closeTime ?? "",
    },
  })

  const phoneNumber = useWatch({ control: form.control, name: "phoneNumber" })
  const phoneChanged = profile.phoneNumber !== phoneNumber
  const phoneUnverified = !profile.phoneVerified

  const handleSubmit = async (values: ProfileValues) => {
    try {
      await updateProfile(values).unwrap()
      toast.success("Profil mis à jour avec succès")
    } catch (err) {
      toast.error(extractErrorMessage(err, "Une erreur est survenue"))
    }
  }

  const handleRequestPhoneOtp = async () => {
    const phone = form.getValues("phoneNumber")
    const e164Phone = phone.startsWith("+") ? phone : `+${phone}`
    try {
      await requestPhoneOtp({ phoneNumber: e164Phone }).unwrap()
      setPendingPhoneNumber(e164Phone)
      setPhoneOtpOpen(true)
    } catch (err) {
      toast.error(extractErrorMessage(err, "Impossible d'envoyer le code"))
    }
  }

  return (
    <>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
          <section className="space-y-4 rounded-xl border bg-white p-5">
            <h2 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
              Informations générales
            </h2>

            <div className="grid gap-4 sm:grid-cols-2">
              <FormField
                control={form.control}
                name="restaurantName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Nom du restaurant</FormLabel>
                    <FormControl>
                      <Input placeholder="Mon Restaurant" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="businessName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      Raison sociale{" "}
                      <span className="text-muted-foreground font-normal">(optionnel)</span>
                    </FormLabel>
                    <FormControl>
                      <Input placeholder="SARL Mon Restaurant" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    Description{" "}
                    <span className="text-muted-foreground font-normal">(optionnel)</span>
                  </FormLabel>
                  <FormControl>
                    <textarea
                      className="flex min-h-[80px] w-full rounded-lg border border-input bg-transparent px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 resize-none"
                      placeholder="Décrivez votre restaurant…"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </section>

          <section className="space-y-4 rounded-xl border bg-white p-5">
            <h2 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
              Contact
            </h2>

            <div className="space-y-1.5">
              <label className="text-sm font-medium flex items-center gap-1.5">
                E-mail
                {profile.emailVerified ? (
                  <span className="inline-flex items-center gap-1 text-xs text-emerald-600 font-normal">
                    <CheckCircle2Icon className="size-3.5" /> Vérifié
                  </span>
                ) : (
                  <span className="inline-flex items-center gap-1 text-xs text-muted-foreground font-normal">
                    <XCircleIcon className="size-3.5" /> Non vérifié
                  </span>
                )}
              </label>
              <Input value={profile.email ?? ""} disabled className="bg-muted/40 cursor-not-allowed" />
              <p className="text-xs text-muted-foreground">
                L&apos;adresse e-mail ne peut pas être modifiée.
              </p>
            </div>

            <FormField
              control={form.control}
              name="phoneNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-1.5">
                    Numéro de téléphone
                    {!phoneChanged && profile.phoneVerified && (
                      <span className="inline-flex items-center gap-1 text-xs text-emerald-600 font-normal">
                        <CheckCircle2Icon className="size-3.5" /> Vérifié
                      </span>
                    )}
                    {!phoneChanged && phoneUnverified && (
                      <span className="inline-flex items-center gap-1 text-xs text-amber-600 font-normal">
                        <XCircleIcon className="size-3.5" /> Non vérifié
                      </span>
                    )}
                  </FormLabel>
                  <div className="flex gap-2">
                    <FormControl className="flex-1">
                      <PhoneInput
                        value={field.value}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                      />
                    </FormControl>
                    {!phoneChanged && phoneUnverified && (
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        className="shrink-0 self-start mt-0.5 gap-1.5"
                        onClick={handleRequestPhoneOtp}
                      >
                        <ShieldCheckIcon className="size-4" />
                        Vérifier
                      </Button>
                    )}
                  </div>
                  <FormMessage />
                  {!phoneChanged && phoneUnverified && (
                    <p className="text-xs text-amber-600">
                      Votre numéro n&apos;est pas encore vérifié. Cliquez sur &quot;Vérifier&quot; pour recevoir un code.
                    </p>
                  )}
                  {phoneChanged && (
                    <p className="text-xs text-muted-foreground">
                      Enregistrez vos modifications pour mettre à jour le numéro.
                    </p>
                  )}
                </FormItem>
              )}
            />
          </section>

          <section className="space-y-4 rounded-xl border bg-white p-5">
            <h2 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
              Horaires &amp; livraison
            </h2>

            <div className="grid gap-4 sm:grid-cols-2">
              <FormField
                control={form.control}
                name="openTime"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Heure d&apos;ouverture</FormLabel>
                    <FormControl>
                      <TimePicker
                        value={field.value}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                        disabled={field.disabled}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="closeTime"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Heure de fermeture</FormLabel>
                    <FormControl>
                      <TimePicker
                        value={field.value}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                        disabled={field.disabled}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid gap-4 sm:grid-cols-2">
              <FormField
                control={form.control}
                name="deliveryFee"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Frais de livraison (FCFA)</FormLabel>
                    <FormControl>
                      <Input type="number" min={0} placeholder="0" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="minimumOrder"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Commande minimum (FCFA)</FormLabel>
                    <FormControl>
                      <Input type="number" min={0} placeholder="0" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </section>

          <div className="flex justify-end">
            <Button type="submit" disabled={isSaving} className="min-w-32 cursor-pointer">
              {isSaving && <Loader2Icon className="animate-spin" />}
              Enregistrer
            </Button>
          </div>
        </form>
      </Form>

      <PhoneOtpDialog
        open={phoneOtpOpen}
        onOpenChange={setPhoneOtpOpen}
        phoneNumber={pendingPhoneNumber}
      />
    </>
  )
}
