import { useMemo } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { CheckCircle2, Loader2, Save, UserCheck, XCircle } from "lucide-react";
import { api } from "@/services/api";
import PhoneInput from "@/components/auth/PhoneInput";
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  CardFooter,
  Button,
  Input,
  Field,
  FieldLabel,
  FieldError,
  FieldGroup,
} from "@edr/ui-common";
import type { ProfileResponse } from "@/types/profile";

const schema = z.object({
  poaName: z.string().optional(),
  poaEmail: z.string().optional(),
  poaPhone: z.string().optional(),
  poaPhoneCountryCode: z.string().optional(),
  poaLocation: z.string().optional(),
  poaAddress: z.string().optional(),
});

type FormData = z.infer<typeof schema>;

function splitPhone(fullPhone?: string | null) {
  if (!fullPhone) return { code: "+251", number: "" };
  const match = fullPhone.match(/^(\+\d{1,3})(.*)$/);
  if (match) return { code: match[1], number: match[2] };
  return { code: "+251", number: fullPhone };
}

export default function TabPowerOfAttorney({
  profile,
}: {
  profile: ProfileResponse;
}) {
  const queryClient = useQueryClient();

  const defaultValues = useMemo((): FormData => {
    const phone = splitPhone(profile.poaPhone);
    return {
      poaName: profile.poaName ?? "",
      poaEmail: profile.poaEmail ?? "",
      poaPhone: phone.number,
      poaPhoneCountryCode: profile.poaPhone ? phone.code : "",
      poaLocation: profile.poaLocation ?? "",
      poaAddress: profile.poaAddress ?? "",
    };
  }, [profile]);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isDirty },
  } = useForm<FormData>({
    resolver: zodResolver(schema),

    values: defaultValues,
  });

  const mutation = useMutation({
    mutationFn: (data: FormData) =>
      api.companies.updateProfile.call({
        poaName: data.poaName || undefined,
        poaPhone:
          data.poaPhone && data.poaPhoneCountryCode
            ? `${data.poaPhoneCountryCode}${data.poaPhone}`
            : undefined,
        poaEmail: data.poaEmail || undefined,
        poaLocation: data.poaLocation || undefined,
        poaAddress: data.poaAddress || undefined,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: api.companies.getProfile.queryKey(),
      });
    },
  });

  const onSubmit = (data: FormData) => mutation.mutate(data);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <UserCheck className="size-5 text-accent" />
          Power of Attorney
        </CardTitle>
        <CardDescription>
          Power of Attorney details are optional. Fill them in if you have an
          authorized representative, or leave blank.
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent>
          <FieldGroup className="gap-4">
            <p className="text-sm text-muted-foreground">
              Power of Attorney details are optional. Fill them in if you have
              an authorized representative, or leave blank.
            </p>

            <Field data-invalid={Boolean(errors.poaName)}>
              <FieldLabel>PoA Full Name</FieldLabel>
              <Input
                placeholder="Authorized Representative Name"
                aria-invalid={Boolean(errors.poaName)}
                {...register("poaName")}
              />
              <FieldError errors={[errors.poaName]} />
            </Field>

            <div className="grid grid-cols-2 gap-4">
              <Field data-invalid={Boolean(errors.poaEmail)}>
                <FieldLabel>PoA Email</FieldLabel>
                <Input
                  type="email"
                  placeholder="poa@company.com"
                  aria-invalid={Boolean(errors.poaEmail)}
                  {...register("poaEmail")}
                />
                <FieldError errors={[errors.poaEmail]} />
              </Field>

              <PhoneInput
                countryCode={{ ...register("poaPhoneCountryCode") }}
                phone={{ ...register("poaPhone"), placeholder: "912345678" }}
                label="PoA Phone"
                countryCodeError={errors.poaPhoneCountryCode}
                phoneError={errors.poaPhone}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Field data-invalid={Boolean(errors.poaLocation)}>
                <FieldLabel>PoA Location</FieldLabel>
                <Input
                  placeholder="City, Country"
                  aria-invalid={Boolean(errors.poaLocation)}
                  {...register("poaLocation")}
                />
                <FieldError errors={[errors.poaLocation]} />
              </Field>

              <Field data-invalid={Boolean(errors.poaAddress)}>
                <FieldLabel>PoA Address</FieldLabel>
                <Input
                  placeholder="Full Address"
                  aria-invalid={Boolean(errors.poaAddress)}
                  {...register("poaAddress")}
                />
                <FieldError errors={[errors.poaAddress]} />
              </Field>
            </div>
          </FieldGroup>
        </CardContent>
        <CardFooter className="flex items-center justify-between gap-4 border-t border-border px-6 py-4">
          <div className="flex items-center gap-2">
            {mutation.isSuccess && (
              <span className="flex items-center gap-1.5 text-sm font-medium text-emerald-600">
                <CheckCircle2 className="size-4" />
                Saved successfully
              </span>
            )}
            {mutation.isError && (
              <span className="flex items-center gap-1.5 text-sm font-medium text-red-600">
                <XCircle className="size-4" />
                Save failed
              </span>
            )}
          </div>
          <div className="flex items-center gap-3">
            <Button
              type="button"
              variant="outline"
              disabled={mutation.isPending || !isDirty}
              onClick={() => reset()}
            >
              Reset
            </Button>
            <Button type="submit" disabled={mutation.isPending}>
              {mutation.isPending ? (
                <>
                  <Loader2 className="size-4 animate-spin" /> Saving...
                </>
              ) : (
                <>
                  <Save className="size-4" /> Save Changes
                </>
              )}
            </Button>
          </div>
        </CardFooter>
      </form>
    </Card>
  );
}
