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, UserCheck, XCircle } from "lucide-react";
import {
  Card,
  Group,
  Stack,
  Title,
  Text,
  TextInput,
  Button,
  Grid,
} from "@mantine/core";
import { api } from "@/services/api";
import { ControlledPhoneField, isValidPhone } from "@/components/PhoneField";
import type { ProfileResponse } from "@/types/profile";

const schema = z.object({
  poaName: z.string().optional(),
  poaEmail: z.string().optional(),
  poaPhone: z
    .string()
    .optional()
    .refine((v) => !v || isValidPhone(v), "Enter a valid phone number"),
  poaLocation: z.string().optional(),
  poaAddress: z.string().optional(),
});

type FormData = z.infer<typeof schema>;

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

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

  const defaultValues = useMemo((): FormData => {
    return {
      poaName: profile.poaName ?? "",
      poaEmail: profile.poaEmail ?? "",
      poaPhone: profile.poaPhone ?? "",
      poaLocation: profile.poaLocation ?? "",
      poaAddress: profile.poaAddress ?? "",
    };
  }, [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({
        poaName: data.poaName || undefined,
        poaPhone: data.poaPhone || undefined,
        poaEmail: data.poaEmail || undefined,
        poaLocation: data.poaLocation || undefined,
        poaAddress: data.poaAddress || undefined,
      }),
    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">
        <UserCheck size={20} />
        <Title order={3}>Power of Attorney</Title>
      </Group>
      <Text c="edr-muted" size="sm" mb="lg">
        Power of Attorney details are optional. Fill them in if you have an
        authorized representative, or leave blank.
      </Text>

      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack gap="md">
          <TextInput
            label="PoA Full Name"
            placeholder="Authorized Representative Name"
            error={errors.poaName?.message}
            {...register("poaName")}
          />

          <Grid>
            <Grid.Col span={6}>
              <TextInput
                label="PoA Email"
                type="email"
                placeholder="poa@company.com"
                error={errors.poaEmail?.message}
                {...register("poaEmail")}
              />
            </Grid.Col>
            <Grid.Col span={6}>
              <ControlledPhoneField
                control={control}
                name="poaPhone"
                label="PoA Phone"
              />
            </Grid.Col>
          </Grid>

          <Grid>
            <Grid.Col span={6}>
              <TextInput
                label="PoA Location"
                placeholder="City, Country"
                error={errors.poaLocation?.message}
                {...register("poaLocation")}
              />
            </Grid.Col>
            <Grid.Col span={6}>
              <TextInput
                label="PoA Address"
                placeholder="Full Address"
                error={errors.poaAddress?.message}
                {...register("poaAddress")}
              />
            </Grid.Col>
          </Grid>
        </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>
  );
}
