"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SharePointPicker = void 0;
const react_1 = require("react");
const uuid_1 = require("uuid");
const input_1 = require("../..//components/ui/input");
const Spinner_1 = require("../../components/Spinner");
const button_1 = require("../../components/ui/button");
const checkbox_1 = require("../../components/ui/checkbox");
const scroll_area_1 = require("../../components/ui/scroll-area");
const openint_1 = require("../../openint");
const messages_1 = require("./messages");
const logoStyle = {
    width: '24px',
    height: '24px',
    marginRight: '8px',
};
// {
//   "name": "cat.jpeg",
//   "webDavUrl": "https://xx.sharepoint.com/xx/cat.jpeg",
//   "webUrl": "https://xx.sharepoint.com/xx/cat.jpeg",
//   "size": 6572,
//   "image": {
//       "width": 275,
//       "height": 183
//   },
//   "photo": {},
//   "id": "017YGEU3UU5R7OHBZLENFKBF5ZETNMO4TN",
//   "parentReference": {
//       "driveId": "b!3kMg8Hd2m0OTS1c0sJBkv67KgeCO3CJHk6yAOJuEXaTHUzBHqAcvQbRx8SJ5arz6",
//       "sharepointIds": {
//           "listId": "473053c7-07a8-412f-b471-f122796abcfa",
//           "webId": "e081caae-dc8e-4722-93ac-80389b845da4",
//           "siteId": "f02043de-7677-439b-934b-5734b09064bf",
//           "siteUrl": "https://xx.sharepoint.com"
//       }
//   },
//   "sharepointIds": {
//       "listItemUniqueId": "e37eec94-2b87-4a23-a097-b924dac7726d",
//       "listItemId": "1",
//       "listId": "473053c7-07a8-412f-b471-f122796abcfa",
//       "webId": "e081caae-dc8e-4722-93ac-80389b845da4",
//       "siteId": "f02043de-7677-439b-934b-5734b09064bf",
//       "siteUrl": "https://xx.sharepoint.com"
//   },
//   "@sharePoint.embedUrl": "https://xx.sharepoint.com/_layouts/15/Embed.aspx?UniqueId=e37eec94%2D2b87%2D4a23%2Da097%2Db924dac7726d",
//   "@sharePoint.endpoint": "https://xx.sharepoint.com/_api/v2.0",
//   "@sharePoint.listUrl": "https://xx.sharepoint.com/Shared%20Documents"
// }
function onSelectMapper(file) {
    return {
        id: file.id,
        name: file.name,
        type: file.size ? 'file' : 'folder',
        driveId: file?.parentReference?.driveId,
        driveGroupId: file?.parentReference?.sharepointIds?.siteId,
    };
}
const SharePointPicker = ({ connectionDetails, options, themeColors, onClose, }) => {
    const [sites, setSites] = (0, react_1.useState)([]);
    const [isLoading, setIsLoading] = (0, react_1.useState)(true);
    const [selectedSite, setSelectedSite] = (0, react_1.useState)(null);
    const [searchTerm, setSearchTerm] = (0, react_1.useState)('');
    const onSelect = async (files) => {
        const selectedFiles = files.map(onSelectMapper);
        await (0, openint_1.persistSelectedFilesOnConnection)(selectedFiles);
        return options.onSelect
            ? options.onSelect(selectedFiles)
            : Promise.resolve();
    };
    const messageManager = (0, react_1.useMemo)(() => {
        return new messages_1.SharePointMessageManager((0, uuid_1.v4)(), connectionDetails.clientId, onSelect, onClose);
    }, [onClose]);
    const createPickerConfig = (0, react_1.useCallback)((siteUrl) => ({
        sdk: '8.0',
        entry: {
            sharePoint: {
                siteUrl: siteUrl,
            },
        },
        authentication: {},
        messaging: {
            origin: window.location.origin,
            channelId: messageManager.getChannelId(),
        },
        selection: {
            mode: options.multiselect ? 'multiple' : 'single',
        },
        typesAndSources: {
            mode: options.folderSelect ? 'folders' : 'all',
            pivots: ['recent', 'shared', 'discover'],
        },
    }), [options.multiselect, options.folderSelect, messageManager]);
    const fetchSites = (0, react_1.useCallback)(async () => {
        setIsLoading(true);
        try {
            const url = 'https://graph.microsoft.com/v1.0/sites?search=*';
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    Authorization: `Bearer ${connectionDetails.accessToken}`,
                    'Content-Type': 'application/json',
                },
            });
            if (!response.ok) {
                throw new Error(`Error fetching followed sites: ${response.statusText}`);
            }
            const data = await response.json();
            // most recent one first
            setSites(data.value
                .sort((a, b) => new Date(b.lastModifiedDateTime).getTime() -
                new Date(a.lastModifiedDateTime).getTime())
                .map((s) => ({
                id: s.id,
                name: s.name,
                displayName: s.displayName,
                url: s.webUrl,
                hostname: s.siteCollection.hostname,
                webUrl: s.webUrl,
            })));
        }
        catch (error) {
            console.error('Failed to fetch SharePoint sites:', error);
        }
        finally {
            setIsLoading(false);
        }
    }, []);
    (0, react_1.useEffect)(() => {
        fetchSites();
    }, [fetchSites]);
    const filteredSites = (0, react_1.useMemo)(() => {
        const searchTerms = searchTerm.toLowerCase().split(/\s+/).filter(Boolean);
        return sites.filter((site) => {
            if (searchTerms.length === 0)
                return true;
            const siteText = `${site.name} ${site.displayName} ${site.url}`.toLowerCase();
            return searchTerms.every((term) => siteText.includes(term));
        });
    }, [sites, searchTerm]);
    const handleSiteSelect = (0, react_1.useCallback)((site) => {
        setSelectedSite(site);
    }, []);
    const handleConfirmSelection = (0, react_1.useCallback)(() => {
        if (selectedSite) {
            const config = createPickerConfig(selectedSite.url);
            messageManager.openPicker(selectedSite.hostname, config);
        }
    }, [selectedSite, createPickerConfig, messageManager]);
    return (<div className="relative p-4" style={{
            color: themeColors.foreground,
            backgroundColor: themeColors.background,
            width: isLoading ? undefined : '420px',
        }}>
      {isLoading ? (<div className="flex h-full items-center justify-center">
          <Spinner_1.Spinner color={themeColors.accent}/>
        </div>) : (<>
          <div className="mb-4 flex items-center justify-between">
            <div className="flex items-center">
              <img 
        // Google one https://pub-c21f3f84c0e943f9806799a566ef9aff.r2.dev/file-picker-logos/google-drive.svg
        src="https://pub-c21f3f84c0e943f9806799a566ef9aff.r2.dev/file-picker-logos/sharepoint.svg" style={logoStyle} alt="SharePoint logo"/>
              <p className="text-xl font-bold" style={{ color: themeColors.primary }}>
                Select Site
              </p>
            </div>
            {options.onClose && (<button onClick={messageManager.close} style={{
                    position: 'absolute',
                    top: '15px',
                    right: '15px',
                    background: 'none',
                    border: 'none',
                    fontSize: '18px',
                    cursor: 'pointer',
                    color: themeColors.foreground,
                }} aria-label="Close">
                ×
              </button>)}
          </div>
          <input_1.Input type="text" placeholder="Search SharePoint sites..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="mb-4" style={{
                backgroundColor: themeColors.background,
                color: themeColors.foreground,
                borderColor: themeColors.border,
                '--tw-ring-color': `${themeColors.primary}40`,
            }}/>
          <scroll_area_1.ScrollArea className="rounded" style={{ borderColor: themeColors.border }}>
            <div style={{ maxHeight: '320px' }}>
              {filteredSites.map((site) => (<div key={site.id} className="site-row flex items-center p-2" style={{
                    '--hover-bg': themeColors.buttonSecondaryHover,
                }}>
                  <checkbox_1.Checkbox id={`site-${site.id}`} checked={selectedSite?.id === site.id} onCheckedChange={() => handleSiteSelect(site)} className="mr-2" style={{
                    backgroundColor: selectedSite?.id === site.id
                        ? themeColors.accent
                        : themeColors.background,
                }}/>
                  <label htmlFor={`site-${site.id}`} className="flex-grow cursor-pointer">
                    <a href={site.webUrl} target="_blank" rel="noopener noreferrer" className="hover:underline">
                      {site.displayName}
                    </a>
                  </label>
                </div>))}
              {/* TODO: add different error if no sites or api call fails using toast */}
              {filteredSites.length === 0 && (<p className="text-gray-500">
                  No SharePoint sites with that name
                </p>)}
            </div>
          </scroll_area_1.ScrollArea>
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <button_1.Button onClick={handleConfirmSelection} disabled={!selectedSite} className="mt-4" style={{
                backgroundColor: themeColors.button,
                color: themeColors.buttonForeground,
                borderColor: themeColors.buttonStroke,
            }}>
              Continue
            </button_1.Button>
          </div>
        </>)}
    </div>);
};
exports.SharePointPicker = SharePointPicker;
//# sourceMappingURL=SharePointPicker.jsx.map