import { ControlledPhoneField, isValidPhone } from "@/components/PhoneField";
import { api } from "@/services/api";
import type {
    CompanyProfileInput,
    CreateCompanyPayload,
} from "@/services/companies.service";
import type { ProfileResponse } from "@/types/profile";
import { zodResolver } from "@hookform/resolvers/zod";
import {
    Button,
    Card,
    Grid,
    Group,
    Stack,
    Text,
    TextInput,
    Title,
} from "@mantine/core";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Building2, CheckCircle2, Save, XCircle } from "lucide-react";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import OnboardingRoleSelect from "./OnboardingRoleSelect";

export const COMPANY_PROFILE_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")
    .refine(isValidPhone, "Enter a valid phone number"),
  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"),
});

export type CompanyProfileFormData = z.infer<typeof COMPANY_PROFILE_SCHEMA>;

interface TabCompanyProfileProps {
  profile?: ProfileResponse;
  mode?: "edit" | "create";
  onCreateSuccess?: () => void;
}

export default function TabCompanyProfile({
  profile,
  mode = "edit",
  onCreateSuccess,
}: TabCompanyProfileProps) {
  const queryClient = useQueryClient();
  const isCreate = mode === "create";
  const [selectedRoles, setSelectedRoles] = useState<string[]>([]);

  const defaultValues = useMemo((): CompanyProfileFormData => {
    if (profile) {
      return {
        companyName: profile.companyName,
        companyEmail: profile.companyEmail ?? "",
        companyPhone: profile.companyPhone ?? "",
        companyLocation: profile.companyLocation,
        companyAddress: profile.companyAddress ?? "",
        tinNumber: profile.tinNumber,
        fanNumber: profile.fanNumber ?? "",
      };
    }
    return {
      companyName: "",
      companyEmail: "",
      companyPhone: "",
      companyLocation: "",
      companyAddress: "",
      tinNumber: "",
      fanNumber: "",
    };
  }, [profile]);

  const {
    register,
    control,
    handleSubmit,
    reset,
    formState: { errors, isDirty },
  } = useForm<CompanyProfileFormData>({
    resolver: zodResolver(COMPANY_PROFILE_SCHEMA),
    values: defaultValues,
  });

  const mutation = useMutation({
    mutationFn: async (data: CompanyProfileFormData) => {
      const base = {
        companyName: data.companyName,
        companyEmail: data.companyEmail,
        companyPhone: data.companyPhone,
        companyLocation: data.companyLocation,
        companyAddress: data.companyAddress,
        tin: data.tinNumber,
        fanNumber: data.fanNumber,
      };

      if (isCreate) {
        // Importer/Exporter -> a "customer" company; Freight Forwarder is its
        // own company type. Both drive the persisted CompanyProfile rows.
        const companyType = selectedRoles.includes("freight_forwarder")
          ? "freight_forwarder"
          : "customer";
        const payload: CreateCompanyPayload = {
          ...base,
          companyType,
          companyProfiles: selectedRoles.map((type) => ({
            type: type as CompanyProfileInput["type"],
          })),
        };
        return api.companies.create.call(payload);
      }
      return api.companies.updateProfile.call(base);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: api.companies.getProfile.queryKey(),
      });
      if (isCreate) {
        onCreateSuccess?.();
      }
    },
  });

  const onSubmit = (data: CompanyProfileFormData) => {
    if (isCreate && selectedRoles.length === 0) return;
    mutation.mutate(data);
  };

  // During onboarding the role selection gates the form: nothing else shows
  // until the user picks Importer/Exporter or Freight Forwarder.
  const showForm = !isCreate || selectedRoles.length > 0;

  return (
    <Stack gap="lg">
      {isCreate ? (
        <OnboardingRoleSelect
          value={selectedRoles}
          onChange={setSelectedRoles}
        />
      ) : null}
      {showForm && (
      <Card padding="lg">
        <Group gap="sm" mb="xs">
          <Building2 size={20} />
          <Title order={3}>Company Profile</Title>
        </Group>
      <Text c="edr-muted" size="sm" mb="lg">
        {isCreate
          ? "Enter your company registration details to get started"
          : "Edit your company registration details"}
      </Text>

      <form onSubmit={handleSubmit(onSubmit)}>
        <Stack gap="md">
          <TextInput
            label="Company Name"
            placeholder="Global Logistics Ltd"
            error={errors.companyName?.message}
            {...register("companyName")}
          />

          <Grid>
            <Grid.Col span={6}>
              <TextInput
                label="Company Email"
                type="email"
                placeholder="ops@company.com"
                error={errors.companyEmail?.message}
                {...register("companyEmail")}
              />
            </Grid.Col>
            <Grid.Col span={6}>
              <ControlledPhoneField
                control={control}
                name="companyPhone"
                label="Company Phone"
                required
              />
            </Grid.Col>
          </Grid>

          <Grid>
            <Grid.Col span={6}>
              <TextInput
                label="Location"
                placeholder="Addis Ababa, Ethiopia"
                error={errors.companyLocation?.message}
                {...register("companyLocation")}
              />
            </Grid.Col>
            <Grid.Col span={6}>
              <TextInput
                label="Address"
                placeholder="Bole Subcity, Woreda 03"
                error={errors.companyAddress?.message}
                {...register("companyAddress")}
              />
            </Grid.Col>
          </Grid>

          <Grid>
            <Grid.Col span={6}>
              <TextInput
                label="TIN Number (10 digits)"
                placeholder="1234567890"
                maxLength={10}
                error={errors.tinNumber?.message}
                {...register("tinNumber")}
              />
            </Grid.Col>
            <Grid.Col span={6}>
              <TextInput
                label="FAN Number (16 digits)"
                placeholder="1234567890123456"
                maxLength={16}
                error={errors.fanNumber?.message}
                {...register("fanNumber")}
              />
            </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 && !isCreate && (
              <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}>
                  {isCreate ? "Failed to create profile" : "Save failed"}
                </Text>
              </Group>
            )}
          </Group>
          <Group gap="md">
            {!isCreate && (
              <Button
                type="button"
                variant="outline"
                disabled={mutation.isPending || !isDirty}
                onClick={() => reset()}
              >
                Reset
              </Button>
            )}
            <Button
              type="submit"
              leftSection={<Save size={16} />}
              loading={mutation.isPending}
            >
              {isCreate ? "Continue" : "Save Changes"}
            </Button>
          </Group>
        </Group>
      </form>
      </Card>
      )}
    </Stack>
  );
}
