import { type FC } from 'react';

import {
  IconArrowLeft,
  IconArrowRight,
  IconMapPin,
} from '@material-hu/icons/tabler';
import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import StateCard from '@material-hu/components/design-system/StateCard';

import { OPEN_GOOGLE_MAPS_URL } from 'src/pages/dashboard/timeTracking/constants';
import {
  EntrySource,
  type SiteCoordinates,
  type SiteLocation,
  type UserSite,
} from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';

import SiteMap from './SiteMap';

type SiteLocationContentProps = {
  siteName: string;
  location: SiteLocation;
};

type SiteLocationMapContentProps = SiteLocationContentProps & {
  siteId: number;
  allSites: UserSite[];
  markingLocation: SiteCoordinates | null;
  entrySource: EntrySource;
  /** When closing the map, pass this so the list keeps this accordion open */
  openAccordionIdToRestore?: string;
  onClose: (accordionToRestore?: string) => void;
};

const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_API_KEY || '';

// Map content with header and close button for the double layout drawer
export const SiteLocationMapContent: FC<SiteLocationMapContentProps> = ({
  siteId,
  siteName,
  location,
  allSites,
  markingLocation,
  entrySource,
  openAccordionIdToRestore,
  onClose,
}) => {
  const { t } = useLokaliseTranslation('time_tracker');
  const { latitude, longitude } = location;

  // Use marking location if available, otherwise fall back to site location
  const mapLocation = markingLocation
    ? markingLocation
    : { latitude, longitude };
  const googleMapsUrl = `${OPEN_GOOGLE_MAPS_URL}${mapLocation.latitude},${mapLocation.longitude}`;

  // Show empty state when entry has no location and source is APP
  const showLocationUnavailable =
    !markingLocation && entrySource === EntrySource.APP;

  return (
    <Stack sx={{ height: '100%', gap: 2 }}>
      {/* Header with hide button and Google Maps link */}
      {!showLocationUnavailable && (
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 2,
          }}
        >
          <Button
            variant="secondary"
            startIcon={<IconArrowLeft size={16} />}
            onClick={() => onClose(openAccordionIdToRestore)}
            sx={{ fontSize: 14 }}
          >
            {t('time_tracker:hide_map')}
          </Button>
          <Link
            href={googleMapsUrl}
            target="_blank"
            rel="noopener noreferrer"
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 0.5,
              fontSize: 14,
              textDecoration: 'none',
              '&:hover': {
                textDecoration: 'underline',
              },
            }}
          >
            {t('time_tracker:view_on_google_maps')}
            <IconArrowRight size={16} />
          </Link>
        </Stack>
      )}

      {/* Map or Empty State */}
      <Stack
        sx={{
          flex: 1,
          minHeight: 300,
          borderRadius: 2,
          overflow: 'hidden',
          border: ({ palette }) =>
            `1px solid ${palette.new.border.neutral.default}`,
        }}
      >
        {showLocationUnavailable && (
          <StateCard
            title={t('time_tracker:marking_location_non_available')}
            description={t(
              'time_tracker:marking_location_non_available_description',
            )}
            variant="warning"
            primaryAction={{
              label: t('general:close'),
              onClick: () => onClose(openAccordionIdToRestore),
            }}
          />
        )}
        {!showLocationUnavailable && GOOGLE_MAPS_API_KEY && (
          <SiteMap
            selectedSiteId={siteId}
            location={location}
            siteName={siteName}
            allSites={allSites}
            markingLocation={markingLocation}
            entrySource={entrySource}
          />
        )}
        {!showLocationUnavailable && !GOOGLE_MAPS_API_KEY && (
          <Stack
            sx={{
              height: '100%',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: ({ palette }) =>
                palette.new.background.layout.default,
              gap: 2,
              p: 3,
            }}
          >
            <IconMapPin size={48} />
            <Typography
              variant="globalS"
              sx={{ textAlign: 'center' }}
            >
              {siteName}
            </Typography>
            <Typography
              variant="globalXS"
              sx={{
                color: ({ palette }) => palette.new.text.neutral.lighter,
                textAlign: 'center',
              }}
            >
              {latitude}, {longitude}
            </Typography>
            <Link
              href={googleMapsUrl}
              target="_blank"
              rel="noopener noreferrer"
              sx={{ mt: 1 }}
            >
              {t('time_tracker:view_on_google_maps')}
            </Link>
          </Stack>
        )}
      </Stack>
    </Stack>
  );
};
