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, User, 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({
  contactPersonName: z.string().min(1, "Contact person name is required"),
  contactPersonPhone: z.string().min(1, "Contact person phone is required"),
  contactPersonPhoneCountryCode: z.string().min(1, "Country code is required"),
});

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 TabContactPerson({ profile }: { profile: ProfileResponse }) {
  const queryClient = useQueryClient();

  const defaultValues = useMemo((): FormData => {
    const phone = splitPhone(profile.contactPersonPhone);
    return {
      contactPersonName: profile.contactPersonName ?? "",
      contactPersonPhone: phone.number,
      contactPersonPhoneCountryCode: phone.code,
    };
  }, [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({
        contactPersonName: data.contactPersonName,
        contactPersonPhone: `${data.contactPersonPhoneCountryCode}${data.contactPersonPhone}`,
      }),
    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">
          <User className="size-5 text-primary" />
          Contact Person
        </CardTitle>
        <CardDescription>Manage the primary contact person for your account</CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent>
          <FieldGroup className="gap-4">
            <Field data-invalid={Boolean(errors.contactPersonName)}>
              <FieldLabel>Full Name</FieldLabel>
              <Input
                placeholder="Jane Smith"
                aria-invalid={Boolean(errors.contactPersonName)}
                {...register("contactPersonName")}
              />
              <FieldError errors={[errors.contactPersonName]} />
            </Field>

            <PhoneInput
              countryCode={{ ...register("contactPersonPhoneCountryCode") }}
              phone={{
                ...register("contactPersonPhone"),
                placeholder: "912345678",
              }}
              countryCodeError={errors.contactPersonPhoneCountryCode}
              phoneError={errors.contactPersonPhone}
              label="Phone Number"
            />
          </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>
  );
}
