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 { Building2, 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({
  companyName: z.string().min(1, "Company name is required"),
  companyEmail: z.string().email("Invalid email address"),
  companyPhone: z.string().min(1, "Company phone is required"),
  companyPhoneCountryCode: z.string().min(1, "Country code is required"),
  companyLocation: z.string().min(1, "Location is required"),
  companyAddress: z.string().min(1, "Address is required"),
  tinNumber: z.string().length(10, "TIN must be exactly 10 digits"),
  fanNumber: z.string().length(16, "FAN must be exactly 16 digits"),
});

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

  const defaultValues = useMemo((): FormData => {
    const phone = splitPhone(profile.companyPhone);
    return {
      companyName: profile.companyName,
      companyEmail: profile.companyEmail ?? "",
      companyPhone: phone.number,
      companyPhoneCountryCode: phone.code,
      companyLocation: profile.companyLocation,
      companyAddress: profile.companyAddress ?? "",
      tinNumber: profile.tinNumber,
      fanNumber: profile.fanNumber ?? "",
    };
  }, [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({
        companyName: data.companyName,
        companyEmail: data.companyEmail,
        companyPhone: `${data.companyPhoneCountryCode}${data.companyPhone}`,
        companyLocation: data.companyLocation,
        companyAddress: data.companyAddress,
        tin: data.tinNumber,
        fanNumber: data.fanNumber,
      }),
    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">
          <Building2 className="size-5 text-primary" />
          Company Profile
        </CardTitle>
        <CardDescription>Edit your company registration details</CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)}>
        <CardContent>
          <FieldGroup className="gap-4">
            <Field data-invalid={Boolean(errors.companyName)}>
              <FieldLabel>Company Name</FieldLabel>
              <Input
                placeholder="Global Logistics Ltd"
                aria-invalid={Boolean(errors.companyName)}
                {...register("companyName")}
              />
              <FieldError errors={[errors.companyName]} />
            </Field>

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

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

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

              <Field data-invalid={Boolean(errors.companyAddress)}>
                <FieldLabel>Address</FieldLabel>
                <Input
                  placeholder="Bole Subcity, Woreda 03"
                  aria-invalid={Boolean(errors.companyAddress)}
                  {...register("companyAddress")}
                />
                <FieldError errors={[errors.companyAddress]} />
              </Field>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <Field data-invalid={Boolean(errors.tinNumber)}>
                <FieldLabel>TIN Number (10 digits)</FieldLabel>
                <Input
                  placeholder="1234567890"
                  maxLength={10}
                  aria-invalid={Boolean(errors.tinNumber)}
                  {...register("tinNumber")}
                />
                <FieldError errors={[errors.tinNumber]} />
              </Field>

              <Field data-invalid={Boolean(errors.fanNumber)}>
                <FieldLabel>FAN Number (16 digits)</FieldLabel>
                <Input
                  placeholder="1234567890123456"
                  maxLength={16}
                  aria-invalid={Boolean(errors.fanNumber)}
                  {...register("fanNumber")}
                />
                <FieldError errors={[errors.fanNumber]} />
              </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>
  );
}
