import type { LucideIcon } from "lucide-react";
import {
  Building2,
  FileCheck,
  Mail,
  MapPin,
  Phone,
  User,
} from "lucide-react";
import { Group, Stack, Text, Divider } from "@mantine/core";

import type { BookingDetail } from "@/types/booking";
import { SectionCard } from "./SectionCard";

interface InfoRowProps {
  icon: LucideIcon;
  label: string;
  value?: string | null;
}

function InfoRow({ icon: Icon, label, value }: InfoRowProps) {
  return (
    <Group justify="space-between" wrap="nowrap" py={6} gap="md">
      <Group gap="xs" wrap="nowrap">
        <Icon size={15} color="var(--mantine-color-gray-5)" />
        <Text size="sm" c="dimmed">
          {label}
        </Text>
      </Group>
      <Text size="sm" fw={600} ta="right" style={{ minWidth: 0 }} truncate>
        {value || "—"}
      </Text>
    </Group>
  );
}

export interface BookingCompanyCardProps {
  booking: BookingDetail;
}

/** Customer (company) information for the booking. */
export function BookingCompanyCard({ booking }: BookingCompanyCardProps) {
  const company = booking.company;

  // Government bookings may not carry a company; show the institution instead.
  if (!company && booking.isGovernment) {
    return (
      <SectionCard icon={Building2} title="Customer" accent="blue">
        <InfoRow
          icon={Building2}
          label="Government"
          value={booking.governmentInstitution}
        />
      </SectionCard>
    );
  }

  if (!company) {
    return (
      <SectionCard icon={Building2} title="Customer" accent="blue">
        <Text size="sm" c="dimmed">
          No customer linked to this booking.
        </Text>
      </SectionCard>
    );
  }

  const companyName = company.companyName ?? company.name ?? company.label;

  const rows: InfoRowProps[] = [
    { icon: FileCheck, label: "TIN", value: company.tin },
    { icon: Mail, label: "Email", value: company.email },
    { icon: Phone, label: "Phone", value: company.phone },
    { icon: MapPin, label: "Address", value: company.address },
    { icon: User, label: "Contact person", value: company.contactPersonName },
    { icon: Phone, label: "Contact phone", value: company.contactPersonPhone },
  ].filter((r) => r.value);

  return (
    <SectionCard
      icon={Building2}
      title="Customer"
      subtitle={companyName}
      accent="blue"
    >
      <Stack gap={0}>
        {rows.length === 0 ? (
          <Text size="sm" c="dimmed">
            No additional company details available.
          </Text>
        ) : (
          rows.map((row, index) => (
            <div key={row.label}>
              {index > 0 && <Divider color="var(--mantine-color-gray-2)" />}
              <InfoRow {...row} />
            </div>
          ))
        )}
      </Stack>
    </SectionCard>
  );
}
