import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { LocationWithRole } from '../../../types/location.entity';
import { App } from '../../../app';
import { apiService } from '../../../services/api.service';

export interface LocationHeaderProps {
  locationWithRole: LocationWithRole;
}

export function LocationHeader({ locationWithRole }: LocationHeaderProps): JSX.Element {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { location } = locationWithRole;

  const handleSalonDashboardClick = async (): Promise<void> => {
    setIsLoading(true);
    try {
      const result = await apiService.getLocationAuthLink(location.id);
      if (result?.authLink) {
        window.open(result.authLink, '_blank');
      }
    } catch (err) {
      alert(__('Failed to get dashboard link. Please try again.', 'timetailor-salon-booking'));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="bg-white shadow rounded-lg rounded-t-none p-6 mb-10 -ml-5">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-medium m-0">{location.businessName}</h1>

        <div className="flex items-center gap-6">
          <a
            href={App.getLocationBookingUrl(location.uuid)}
            target="_blank"
            rel="noopener noreferrer"
            className="underline"
          >
            {__('Booking Page', 'timetailor-salon-booking')}
          </a>

          <button
            className="button button-primary button-large"
            onClick={handleSalonDashboardClick}
            disabled={isLoading}
          >
            {__('Salon Dashboard', 'timetailor-salon-booking')}
          </button>
        </div>
      </div>
    </div>
  );
}
