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, Save, User, XCircle } from "lucide-react";
import {
  Card,
  Group,
  Stack,
  Title,
  Text,
  TextInput,
  Button,
} from "@mantine/core";
import { api } from "@/services/api";
import { ControlledPhoneField, isValidPhone } from "@/components/PhoneField";
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")
    .refine(isValidPhone, "Enter a valid phone number"),
});

type FormData = z.infer<typeof schema>;

interface TabContactPersonProps {
  profile: ProfileResponse;
  mode?: "edit" | "onboarding";
  onContinue?: () => void;
}

export default function TabContactPerson({ profile, mode = "edit", onContinue }: TabContactPersonProps) {
  const queryClient = useQueryClient();

  const defaultValues = useMemo((): FormData => {
    return {
      contactPersonName: profile.contactPersonName ?? "",
      contactPersonPhone: profile.contactPersonPhone ?? "",
    };
  }, [profile]);

  const {
    register,
    control,
    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.contactPersonPhone,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: api.companies.getProfile.queryKey() });
      if (mode === "onboarding") onContinue?.();
    },
  });

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

  return (
    <Card padding="lg">
      <Group gap="sm" mb="xs">
        <User size={20} />
        <Title order={3}>Contact Person</Title>
      </Group>
      <Text c="edr-muted" size="sm" mb="lg">
        Manage the primary contact person for your account
      </Text>

      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack gap="md">
          <TextInput
            label="Full Name"
            placeholder="Jane Smith"
            error={errors.contactPersonName?.message}
            {...register("contactPersonName")}
          />

          <ControlledPhoneField
            control={control}
            name="contactPersonPhone"
            label="Phone Number"
            required
          />
        </Stack>

        <Group
          justify="space-between"
          mt="xl"
          pt="md"
          style={{ borderTop: "1px solid var(--mantine-color-edr-border-0)" }}
        >
          <Group gap="xs">
            {mutation.isSuccess && (
              <Group gap={6} c="green">
                <CheckCircle2 size={16} />
                <Text size="sm" fw={500}>Saved successfully</Text>
              </Group>
            )}
            {mutation.isError && (
              <Group gap={6} c="red">
                <XCircle size={16} />
                <Text size="sm" fw={500}>Save failed</Text>
              </Group>
            )}
          </Group>
          <Group gap="md">
            {mode === "edit" && (
              <Button
                type="button"
                variant="outline"
                disabled={mutation.isPending || !isDirty}
                onClick={() => reset()}
              >
                Reset
              </Button>
            )}
            <Button
              type="submit"
              leftSection={<Save size={16} />}
              loading={mutation.isPending}
            >
              {mode === "onboarding" ? "Continue" : "Save Changes"}
            </Button>
          </Group>
        </Group>
      </form>
    </Card>
  );
}
