import { Box, Group, Text } from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { ArrowRight, Truck, AlertTriangle } from "lucide-react";
import { memo } from "react";
import { Link } from "react-router-dom";
import { api } from "@/services/api";
import type { ProfileResponse } from "@/types/profile";
import { cv } from "../constants";

const REQUIRED_FIELDS: (keyof ProfileResponse)[] = [
  "companyEmail",
  "companyPhone",
  "companyAddress",
  "fanNumber",
  "contactPersonName",
  "contactPersonPhone",
  "generalManagerName",
  "generalManagerEmail",
  "generalManagerPhone",
];

function isProfileIncomplete(profile?: ProfileResponse | null): boolean {
  if (!profile) return true;
  return REQUIRED_FIELDS.some((field) => !profile[field]);
}

interface SetupPromptProps {
  show: boolean;
}

export const SetupPrompt = memo(function SetupPrompt({ show }: SetupPromptProps) {
  const profileQuery = useQuery(
    api.companies.getProfile.queryOptions({ retry: false }),
  );

  const incomplete = !profileQuery.isPending && isProfileIncomplete(profileQuery.data);

  if (!show && !incomplete) return null;

  return (
    <Box className="rounded-2xl border border-edr-border bg-gradient-to-r from-edr-blue/5 to-edr-green/5 px-7 py-6">
      <Group justify="space-between" align="center" wrap="nowrap">
        <Box className="flex-1">
          <Group gap={6} align="center" mb={6}>
            {incomplete && <AlertTriangle size={16} color={cv("edr-orange")} />}
            <Text fz={15} fw={700} c="edr-text">
              {incomplete ? "Complete Your Profile" : "Setup your Company Profile"}
            </Text>
          </Group>
          <Text fz={13} c="edr-muted" mb={12}>
            {incomplete
              ? "Your company profile is incomplete. Fill in the missing details to unlock all features."
              : "Complete your company information to unlock all features and start booking shipments."}
          </Text>
          <Link to="/settings" className="no-underline">
            <Group gap={8} align="center" className="w-fit">
              <Text fz={13} fw={600} c="edr-green.7">
                {incomplete ? "Complete Profile" : "Complete Setup"}
              </Text>
              <ArrowRight size={16} color={cv("edr-green.7")} />
            </Group>
          </Link>
        </Box>
        <Box className="hidden shrink-0 sm:block">
          <Truck size={48} color={cv("edr-blue")} opacity={0.3} />
        </Box>
      </Group>
    </Box>
  );
});
