
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Breadcrumb,
    BreadcrumbItem,
    BreadcrumbLink,
    BreadcrumbList,
    BreadcrumbPage,
    BreadcrumbSeparator,
} from '@/components/ui/breadcrumb';
import { Button } from '@/components/ui/button';
import { toast } from '@/hooks/use-toast';
import { StartESILogin, ESILoginStatus } from 'wailsjs/go/main/App';

interface HeaderProps {
  title: string;
  breadcrumbs?: Array<{
    label: string;
    path?: string;
  }>;
}

export const Header = ({ title, breadcrumbs = [] }: HeaderProps) => {
  const navigate = useNavigate();
  const [status, setStatus] = useState<string>('');

  useEffect(() => {
    ESILoginStatus().then(setStatus).catch(() => setStatus(''));
  }, []);

  const handleLogin = async () => {
    try {
      await StartESILogin();
      toast({ title: 'EVE Login', description: 'Complete login in your browser. Reopen menu to refresh status.' });
    } catch (e: any) {
      toast({ title: 'Login failed', description: String(e), variant: 'destructive' });
    }
  };

  return (
    <div className="flex-shrink-0 py-4 px-4 border-b border-purple-500/20">
      {/* Breadcrumb Navigation */}
      {breadcrumbs.length > 0 && (
        <div className="mb-3">
          <Breadcrumb>
            <BreadcrumbList>
              {breadcrumbs.map((crumb, index) => (
                <React.Fragment key={index}>
                  {index > 0 && <BreadcrumbSeparator className="text-slate-400" />}
                  <BreadcrumbItem>
                    {crumb.path ? (
                      <BreadcrumbLink
                        onClick={() => navigate(crumb.path!)}
                        className="text-purple-200 hover:text-white cursor-pointer"
                      >
                        {crumb.label}
                      </BreadcrumbLink>
                    ) : (
                      <BreadcrumbPage className="text-white font-semibold">
                        {crumb.label}
                      </BreadcrumbPage>
                    )}
                  </BreadcrumbItem>
                </React.Fragment>
              ))}
            </BreadcrumbList>
          </Breadcrumb>
        </div>
      )}
      
      {/* Title + EVE SSO */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-white">{title}</h1>
        <div className="flex items-center gap-2">
          <span className="text-sm text-slate-300">{status || 'EVE: not logged in'}</span>
          <Button size="sm" className="bg-purple-600 hover:bg-purple-700" onClick={handleLogin}>Log in</Button>
        </div>
      </div>
    </div>
  );
};
