import type { User } from 'oidc-client-ts';
import { useEffect, useState } from 'react';
import './App.css';
import { AppSidebar } from './AppSidebar';
import { getUser, handleCallback, logout } from './auth/authService';
import ActiveQuery from './components/ActiveQuery';
import AlertError from './components/AlertError';
import LoginModal from './components/LoginModal';
import { Map } from './components/Map';
import { Parameters, type ParameterValues } from './components/Parameters';
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from './components/ui/breadcrumb';
import { Button } from './components/ui/button';
import { Separator } from './components/ui/separator';
import { SidebarInset, SidebarProvider, SidebarTrigger } from './components/ui/sidebar';

const fetchData = async (user: User, baseQueyrUri: string, parameters: ParameterValues, method: string = 'GET') => {
  const accessToken = user.access_token;
  const queryString = new URLSearchParams();
  queryString.append('listing_type', parameters.listing_type)
  if (parameters.min_bedrooms) {
    queryString.append('min_bedrooms', parameters.min_bedrooms.toString());
  }
  if (parameters.max_bedrooms) {
    queryString.append('max_bedrooms', parameters.max_bedrooms.toString())
  }
  if (parameters.max_price) {
    queryString.append("max_price", parameters.max_price.toString());
  }
  if (parameters.min_price) {
    queryString.append("min_price", parameters.min_price.toString());
  }
  if (parameters.min_sqm) {
    queryString.append("min_sqm", parameters.min_sqm.toString());
  }

  const response = await fetch(baseQueyrUri + '?' + queryString,
    {
      method: method,
      headers: {
        'Authorization': `Bearer ${accessToken}`, // Pass the token
        'Content-Type': 'application/json',
      },
    }
  );
  if (!response.ok) {
    throw new Error('Error: ' + response.status);
  }
  const data: Response = await response.json();
  return data;
};


function App() {
  const [listingData, setListingData] = useState({});
  const [taskID, setTaskID] = useState<string | null>(null);
  const [user, setUser] = useState<User | null>(null);
  const [isParametersModalOpen, setIsParametersModalOpen] = useState(true);
  const [queryParameters, setQueryParameters] = useState<ParameterValues | null>(null);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [alertDialogIsOpen, setAlertDialogIsOpen] = useState(false);

  useEffect(() => {
    // Check if this is a callback from Authentik (after login)
    if (window.location.pathname === '/callback') {
      handleCallback().then(() => {
        window.location.href = '/'; // Redirect to home after login
      });
      return;
    }

    // Load user data
    getUser().then(setUser);
  }, []);

  if (!user) {
    return <LoginModal isOpen={user === null} />
  }

  const onSubmit = async (action: 'fetch-data' | 'visualize', parameters: ParameterValues) => {
    // Fetch listing data
    setQueryParameters(parameters)
    setIsParametersModalOpen(false)
    let data = null;
    if (action === 'visualize') {
      try {
        data = await fetchData(user, "/api/listing_geojson", parameters);
      } catch (error) {
        setSubmitError(error.message)
        setAlertDialogIsOpen(true)
      }
      if (data) {
        setListingData(data);
      }
    } else if (action === 'fetch-data') {
      try {
        data = await fetchData(user, "/api/refresh_listings", parameters, 'POST');
      } catch (error) {
        setSubmitError(error.message)
        setAlertDialogIsOpen(true)
      }
      if (data) {
        // @ts-expect-error
        setTaskID(data.task_id)
      }
    }
    console.log(data)
  }

  return (
    <>
      <SidebarProvider defaultOpen={false}>
        <AppSidebar />
        <SidebarInset>
          <header className="flex h-16 shrink-0 items-center gap-2 border-b px-4">
            <SidebarTrigger className="-ml-1" />
            <Separator
              orientation="vertical"
              className="mr-2 data-[orientation=vertical]:h-4"
            />
            <Breadcrumb>
              <BreadcrumbList>
                <BreadcrumbItem className="hidden md:block">
                  <BreadcrumbLink href="#">
                    Building Your Application
                  </BreadcrumbLink>
                </BreadcrumbItem>
                <BreadcrumbSeparator className="hidden md:block" />
                <BreadcrumbItem>
                  <BreadcrumbPage>Data Fetching</BreadcrumbPage>
                </BreadcrumbItem>
              </BreadcrumbList>
            </Breadcrumb>
          </header>
          <div className="flex flex-col h-screen w-full">
            <div className="flex gap-2 p-2 bg-gray-100">
              <h1>Welcome, {user.profile.name}!</h1>
              <Button onClick={logout}>Logout</Button>
              <Parameters onSubmit={onSubmit} isOpen={isParametersModalOpen} setIsOpen={setIsParametersModalOpen} />
              <ActiveQuery taskID={taskID} />
              <AlertError message={submitError} open={alertDialogIsOpen} setIsOpen={setAlertDialogIsOpen} />
            </div>
            {Object.keys(listingData).length > 0 &&
              <div className="flex-1 w-full relative" style={{ minHeight: 0, marginBottom: '8rem' }}>
                <Map listingData={listingData} queryParameters={queryParameters} />
              </div>
            }
          </div>



        </SidebarInset>
      </SidebarProvider>
    </>
  )
}

export default App
