import { useMemo, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Building2, CheckCircle2, Save, XCircle } from "lucide-react";
import {
  Button,
  Card,
  Group,
  SimpleGrid,
  Text,
  Title,
} from "@mantine/core";
import { api } from "@/services/api";
import type { ProfileResponse } from "@/types/profile";
import RoleCard from "./RoleCard";
import { rolesForCompanyType } from "./companyRoles";

interface CompanyRolesCardProps {
  profile: ProfileResponse;
}

export default function CompanyRolesCard({ profile }: CompanyRolesCardProps) {
  const queryClient = useQueryClient();

  const options = useMemo(
    () => rolesForCompanyType(profile.companyType),
    [profile.companyType],
  );

  // Roles already persisted (active + locked), keyed by type -> reference.
  const activeByType = useMemo(() => {
    const map = new Map<string, string>();
    for (const p of profile.companyProfiles) map.set(p.type, p.reference);
    return map;
  }, [profile.companyProfiles]);

  const [selected, setSelected] = useState<Set<string>>(new Set());

  const toggle = (type: string) => {
    if (activeByType.has(type)) return; // add-only: active roles are locked
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(type)) next.delete(type);
      else next.add(type);
      return next;
    });
  };

  const mutation = useMutation({
    mutationFn: (types: string[]) =>
      api.companies.addCompanyProfiles.call({ types }),
    onSuccess: () => {
      setSelected(new Set());
      queryClient.invalidateQueries({
        queryKey: api.companies.getProfile.queryKey(),
      });
      queryClient.invalidateQueries({
        queryKey: api.companies.getInfo.queryKey(),
      });
    },
  });

  const handleSave = () => {
    if (selected.size === 0) return;
    mutation.mutate(Array.from(selected));
  };

  return (
    <Card padding="lg">
      <Group gap="sm" mb="xs">
        <Building2 size={20} />
        <Title order={3}>Operating Roles</Title>
      </Group>
      <Text c="edr-muted" size="sm" mb="lg">
        {profile.companyType === "customer"
          ? "Select the service(s) your company operates as — importer, exporter and/or freight forwarder."
          : "Your company's operational role."}
      </Text>

      {options.length === 0 ? (
        <Text size="sm" c="edr-muted">
          Role management for this company type is coming soon.
        </Text>
      ) : (
        <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
          {options.map((opt) => {
            const isActive = activeByType.has(opt.type);
            return (
              <RoleCard
                key={opt.type}
                label={opt.label}
                description={opt.description}
                icon={opt.icon}
                selected={selected.has(opt.type)}
                locked={isActive}
                lockedNote={
                  isActive ? `Active · ${activeByType.get(opt.type)}` : undefined
                }
                onClick={() => toggle(opt.type)}
              />
            );
          })}
        </SimpleGrid>
      )}

      {options.length > 0 && (
        <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}>
                  Profile updated
                </Text>
              </Group>
            )}
            {mutation.isError && (
              <Group gap={6} c="red">
                <XCircle size={16} />
                <Text size="sm" fw={500}>
                  Failed to update profile
                </Text>
              </Group>
            )}
          </Group>
          <Button
            type="button"
            leftSection={<Save size={16} />}
            loading={mutation.isPending}
            disabled={selected.size === 0}
            onClick={handleSave}
          >
            {selected.size > 1 ? "Add Roles" : "Add Role"}
          </Button>
        </Group>
      )}
    </Card>
  );
}
