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 { Briefcase, CheckCircle2, Loader2, Save, 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({
  generalManagerName: z.string().min(1, "GM name is required"),
  generalManagerEmail: z.string().email("Invalid GM email"),
  generalManagerPhone: z.string().min(1, "GM phone is required"),
  generalManagerPhoneCountryCode: 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 TabGeneralManager({ profile }: { profile: ProfileResponse }) {
  const queryClient = useQueryClient();

  const defaultValues = useMemo((): FormData => {
    const phone = splitPhone(profile.generalManagerPhone);
    return {
      generalManagerName: profile.generalManagerName ?? "",
      generalManagerEmail: profile.generalManagerEmail ?? "",
      generalManagerPhone: phone.number,
      generalManagerPhoneCountryCode: 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({
        generalManagerName: data.generalManagerName,
        generalManagerEmail: data.generalManagerEmail,
        generalManagerPhone: `${data.generalManagerPhoneCountryCode}${data.generalManagerPhone}`,
      }),
    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">
          <Briefcase className="size-5 text-primary" />
          General Manager
        </CardTitle>
        <CardDescription>Manage the general manager information</CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent>
          <FieldGroup className="gap-4">
            <Field data-invalid={Boolean(errors.generalManagerName)}>
              <FieldLabel>Full Name</FieldLabel>
              <Input
                placeholder="Abebe Bikila"
                aria-invalid={Boolean(errors.generalManagerName)}
                {...register("generalManagerName")}
              />
              <FieldError errors={[errors.generalManagerName]} />
            </Field>

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

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