import React from 'react';
import {
  Button,
  ButtonWithDropdown,
  ButtonWithPopover,
  Checkbox,
  Icon,
  Modal,
  QTip,
  Select,
  Tabs,
  TextArea,
  TextField,
  ToolbarButton,
  Accordion,
  Alert,
  ButtonGroup,
  Carousel,
  Collapse,
  InputGroup,
  ProgressBar,
  SeeqActionDropdown,
  Slider,
} from '@seeqdev/qomponents';
import ComplexSelectExample, { SelectOption } from './ComplexSelectExample';

const availableThemes = [
  { display: 'Analysis', value: 'color_analysis' },
  { display: 'Topic', value: 'color_topic' },
  { display: 'DataLab', value: 'color_datalab' },
];

const options = [
  { value: '1', label: 'Beginner' },
  { value: '2', label: 'Advanced' },
  { value: '3', label: 'Expert' },
];

const Trigger = ({ label }: { label: string }) => (
  <div className="flex justify-start items-center border-b px-2 tw:text-sq-theme-dark">
    <Icon icon="fc-arrow-dropdown" extraClassNames="tw:text-sq-theme-dark mr-[0.5rem] text-[0.75rem]" type="text" />
    {label}
  </div>
);

const accordionItems = [
  {
    value: 'phone',
    id: 'phone',
    itemTestId: 'phonecall',
    trigger: <Trigger label="Phone" />,
    content: (
      <div className="p-2 text-[0.8125rem] dark:tw-text-sq-white">
        If you need to reach us, please call us at 555-555-5555.
      </div>
    ),
  },
  {
    value: 'email',
    id: 'email',
    itemTestId: 'email',
    trigger: <Trigger label="Email" />,
    content: (
      <div className="p-2 text-[0.8125rem] dark:text-sq-white">
        If you need to reach us, please mail example@seeqtest.com
      </div>
    ),
  },
  {
    value: 'address',
    id: 'address',
    itemTestId: 'address',
    trigger: <Trigger label="Address" />,
    content: (
      <div className="p-2 text-[0.8125rem] dark:tw-text-sq-white">
        If you need to reach us, please visit us at 1234 Main St., Anytown, USA.
      </div>
    ),
  },
];

const renderData = (text: string) => (
  <div className="tw:text-sq-gray dark:tw-text-sq-white p-6">
    <p className="mb-5 text-[0.9375rem] leading-normal">{text}</p>
  </div>
);

const tabsList = [
  {
    id: 'plugins',
    label: 'Plugins',
    icon: 'fc-data',
    content: renderData("Here's where you can find all the plugins you need. Enjoy!"),
  },
  {
    id: 'addons',
    label: 'Addons',
    icon: 'fc-gears-2',
    content: renderData("Here's where you can find all the addons you need. Enjoy!"),
  },
  {
    id: 'shelf',
    label: 'Shelf',
    icon: 'fc-workbook-lock',
    content: renderData("Here's where you can find all the private documents you need. Enjoy!"),
  },
];

function Example() {
  /**
   * Theming is supported "out of the box". To apply a theme wrap your addOn in a div and assign the class that
   * matched the desired theme:
   * - color_analysis for Analysis styled qomponents (green)
   * - color_topic for Topic styled qomponents (blue)
   * - DataLab for DataLab styled qomponents (orange)
   */
  const [theme, setTheme] = React.useState('color_analysis');
  /**
   * qomponents also support tw-dark. To render qomponents using tw-dark wrap your addOn in a div and assign the
   * class "tw-dark" for dark-mode or "tw-light" for light mode.
   */
  const [mode, setMode] = React.useState('tw-light');

  const [btGroupType, setBtGroupType] = React.useState('left');

  /**
   * This example uses controlled inputs (https://blog.logrocket.com/controlled-vs-uncontrolled-components-in-react/)
   */
  const [textFieldValue, setTextFieldValue] = React.useState('');
  const [textAreaValue, setTextAreaValue] = React.useState('');
  const [selectValue, setSelectValue] = React.useState();
  const [complexSelectedValue, setComplexSelectedValue] = React.useState<SelectOption>();
  const [alertDisplay, setAlertDisplay] = React.useState('success');
  const [easeOfUse, setEaseOfUse] = React.useState(false);
  const [lookAndFeel, setLookAndFeel] = React.useState(false);
  const [speed, setSpeed] = React.useState(false);
  const [help, setHelp] = React.useState('phone');
  const [openDropdown, setOpenDropdown] = React.useState('');
  const [openPopver, setOpenPopover] = React.useState('');
  const [modalOpen, setModalOpen] = React.useState(false);
  const [modalTitle, setModalTitle] = React.useState('Modal Title');
  const [activeTab, setActiveTab] = React.useState('plugins');
  const [collapseVisible, setCollapseVisible] = React.useState(false);
  const [inputGroupValue, setInputGroupValue] = React.useState('');
  const [sliderValue, setSliderValue] = React.useState<number>(50);

  return (
    // outer-wrapper div that assigns the mode (tw-dark or light) as well as the theme
    <div className={`backdrop ${mode} ${theme}`}>
      {/*add the QTip component at the very top level or your application to ensure your tooltips display as expected!*/}
      <QTip />
      <div className="flex-container">
        <div className="scroll-container">
          <div className="header">qomponents - form example</div>
          <div>Use this example to see qomponents in actions.</div>
          No libraries other than Seeq's qomponents (and of course React) are used to create this example, however
          minimal CSS is used to create an appealing form - you can find all that CSS in index.css.
          <p className="mb-10">
            <b>A note on CSS:</b> Seeq's qomponents come fully styled and ready to use. While it is tempting to use the
            available <i>extraClassNames</i> property to provide yet additional styling we strongly advise you to use
            this property to provide only width, margins and padding. This will ensure for a smooth upgrade experience
            when Seeq's look and feel changes. <br />
            Tip: to indicate missing or wrong user input use the <i>showError</i> property available on TextField,
            TextArea, as well as Select.
          </p>
          <p className="mb-10">
            Using FontAwesome? You can pass FontAwesome Icons to the qomponent Icon component
            <Icon icon="fa-regular fa-face-smile" extraClassNames="ml-10" />
          </p>
          <div className="mb-10">
            <a
              href="#"
              onClick={() => setMode(mode === 'tw-light' ? 'tw-dark' : 'tw-light')}
              // this is how you display a q-tip for an element that doesn't come with an "out-of the box" tooltip
              // property:
              data-qtip-text="Toggle Dark/Light Mode."
              // the position is optional and defaults to top
              data-qtip-position="bottom">
              <Icon icon="fc-sun" extraClassNames="mr-10" />
              Click to toggle to {mode === 'tw-light' ? 'Dark Mode' : 'Light Mode'}
            </a>
          </div>
          <div className="formRow">
            <div className="labelWidth">Select theme:</div>
            {availableThemes.map((t) => (
              <Checkbox
                key={t.value}
                type="radio"
                checked={theme === t.value}
                value={t.value}
                label={t.display}
                onChange={(e) => setTheme(e.target.value)}
                extraClassNames="mr-10"
              />
            ))}
          </div>
          <div className="formRow">
            <div className="labelWidth">AddOn Name</div>
            <TextField
              placeholder="you must enter a name"
              extraClassNames="formElementWidth"
              value={textFieldValue}
              showError={textFieldValue === ''}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTextFieldValue(e.target.value)}
            />
          </div>
          <div className="formRow">
            <div className="labelWidth">Description</div>
            <TextArea
              value={textAreaValue}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTextAreaValue(e.target.value)}
              extraClassNames="formElementWidth"
              placeholder="provide some text here"
            />
          </div>
          <div className="formRow">
            <div className="labelWidth">Goals</div>
            <div className="formColumn">
              <div>
                <Checkbox checked={easeOfUse} label="Ease of Use" onChange={() => setEaseOfUse(!easeOfUse)} />
                <Checkbox
                  checked={lookAndFeel}
                  label="Improved Look & Feel"
                  onChange={() => setLookAndFeel(!lookAndFeel)}
                />
                <Checkbox checked={speed} label="Speedy Development" onChange={() => setSpeed(!speed)} />
              </div>
            </div>
          </div>
          <div className="formRow">
            <div className="labelWidth">Level</div>
            <Select
              value={selectValue}
              extraClassNames="formElementWidth"
              onChange={(selectValue) => setSelectValue(selectValue)}
              options={options}
              placeholder="please choose"
            />
          </div>
          <div className="formRow">
            <div className="labelWidth">Advanced</div>
            <ComplexSelectExample
              value={complexSelectedValue}
              onChange={(selectedOption: SelectOption) => setComplexSelectedValue(selectedOption)}
            />
          </div>
          <div className="formRow">
            <div className="labelWidth">Website tools</div>
            <div className="formElementWidth border rounded-sm">
              <Tabs
                stretchTabs={true}
                activeTab={activeTab}
                onTabSelect={setActiveTab}
                defaultActiveTab="data"
                tabs={tabsList}
              />
            </div>
          </div>
          <div className="formRow">
            <div className="labelWidth">Get help</div>
            <div className="formElementWidth border rounded-sm">
              <Accordion
                accordionItems={accordionItems}
                value={help}
                testId="basic-accordion1"
                onItemSelect={(value) => setHelp(value)}
              />
            </div>
          </div>
          <div className="formRow">
            <div className="labelWidth">Tools</div>
            <div className="formElementWidth formRow border rounded-sm p-4 flex justify-center">
              <ToolbarButton
                icon="fc-y-axis"
                label="Analyzer"
                testId="basic-analyzer"
                tooltipText="Analize data from any csv document"
                hasArrow
                tooltipOptions={{ position: 'top', delay: 0 }}
                isHtmlTooltip={false}
                popoverContent={
                  <div className="text-sm dark:text-white">
                    <p className="p-2">Select file from your computer or google drive</p>
                    <Button type="button" label="Click to select file" />
                  </div>
                }
              />
              <ToolbarButton
                icon="fc-sun"
                label={mode === 'light' ? 'Dark Mode' : 'Light Mode'}
                testId="basic-toggler"
                isActive={mode === 'tw-light'}
                tooltipText="Toggle light and dark modes"
                onClick={() => setMode(mode === 'tw-light' ? 'tw-dark' : 'tw-light')}
                tooltipOptions={{ position: 'top', delay: 0 }}
                isHtmlTooltip={false}
              />
              <ToolbarButton
                icon="fc-marker"
                label="Language"
                testId="basic-language-changer"
                tooltipText="Disabled toolbar to change website language"
                tooltipOptions={{ position: 'top', delay: 0 }}
                disabled
              />
            </div>
          </div>
          <div className="formRow">
            <div className="labelWidth">Take action</div>
            <div className="formElementWidth">
              <ButtonWithDropdown
                onOpenChange={(isOpen) => setOpenDropdown(isOpen ? 'dropdown-1' : '')}
                isOpen={openDropdown === 'dropdown-1'}
                triggerIcon={
                  <Icon
                    icon="fc-more"
                    type="text"
                    extraClassNames="tw-text-sq-text-color dark:tw-text-sq-white w-[18px]"
                  />
                }
                containerTestId="basic-dropdown1"
                tooltip="See actions to take for plugins"
                tooltipDelay={0}
                hasArrow
                tooltipPlacement="top"
                dropdownItems={[
                  { label: 'Create', icon: 'fc-add-row', onClick: () => setOpenDropdown('') },
                  { label: 'Update', icon: 'fc-asset-tree', onClick: () => setOpenDropdown(''), hasDivider: true },
                  {
                    label: 'Sort',
                    icon: 'fc-search-power',
                    onClick: () => setOpenDropdown(''),
                    subMenuItems: [
                      { label: 'Ascending', iconClass: 'fc-arrow_up', onClick: () => setOpenDropdown('') },
                      { label: 'Descending', iconClass: 'fc-arrow_down', onClick: () => setOpenDropdown('') },
                    ],
                  },
                  { label: 'Delete', icon: 'fc-delete', onClick: () => setOpenDropdown('') },
                ]}
              />
            </div>
          </div>
          <div className="formRow mt-4">
            <div className="labelWidth">More information</div>
            <div className="formElementWidth">
              <ButtonWithPopover
                trigger={<Icon type="text" icon="fc-circle_info" />}
                containerTestId="basic-popover-1"
                isOpen={openPopver === 'basic-popover-1'}
                onOpenChange={(isOpen) => setOpenPopover(isOpen ? 'basic-popover-1' : '')}
                isHoverEnabled={false}
                align="start"
                tooltipPlacement="top"
                hasArrow
                isHtmlTooltip={false}>
                <div className="text-sm dark:text-white w-72 p-4">
                  <p className="font-bold">What are plugins?</p>
                  Plugins are modular software components that extend the functionality of an application. They allow
                  users to add new features or customize existing ones. Plugins can be easily integrated into an
                  application and provide a way to enhance its capabilities without modifying the core codebase.Plugins
                  are modular software components that extend the functionality of an application.
                </div>
              </ButtonWithPopover>
            </div>
          </div>
          <div className="formRow mt-4">
            <div className="labelWidth">Accept terms</div>
            <div className="formElementWidth">
              <Button
                onClick={() => {
                  setModalOpen(true);
                }}
                label="View terms of use"
              />
              <Modal
                open={modalOpen}
                onClose={() => setModalOpen(false)}
                title="Terms of use"
                titleIcon="fc-circle_info"
                isTitleEditable
                onTitleChanged={(event) => setModalTitle(event.target.value)}
                hideCloseIcon={false}
                size="lg"
                customButton={true}
                customButtonLabel="Back">
                <div>
                  <p>
                    By using this website, you agree to the following terms of use: Lorem ipsum dolor sit amet,
                    consectetur adipiscing elit. Sed euismod, justo id aliquet aliquam, elit enim tincidunt mauris, nec
                    aliquam nunc elit vitae nunc. Sed vitae fringilla mauris. Nulla facilisi. Sed auctor, nunc vel
                    aliquet luctus, nisl nunc tincidunt nunc, id lacinia mauris metus id nunc. Sed auctor, nunc vel
                    aliquet luctus, nisl nunc tincidunt nunc, id lacinia mauris metus id nunc.
                  </p>
                </div>
              </Modal>
            </div>
          </div>
          <div className="formRow mt-8">
            <div className="labelWidth">Button example</div>
            <div className="formElementWidth">
              <div className="flex gap-2 mb-4">
                <Button label="Show Success" onClick={() => setAlertDisplay('success')} variant="theme" />
                <Button label="Show Cancel" onClick={() => setAlertDisplay('cancel')} variant="danger" />
                <Button label="Show Info" onClick={() => setAlertDisplay('info')} variant="outline" />
              </div>
            </div>
          </div>
          {/* Alert Example: Show info, success, or warning based on form submission */}
          <div className="formRow mt-8">
            <div className="labelWidth">Alert example</div>
            <div className="formElementWidth">
              {alertDisplay === 'success' && (
                <Alert variant="theme" testId="alert-success" dismissible>
                  <div className="font-bold">Submission Successful</div>
                  <div>
                    Your add-on details have been submitted successfully. Thank you for contributing to the Seeq Add-on
                    ecosystem!
                  </div>
                </Alert>
              )}
              {alertDisplay === 'cancel' && (
                <Alert variant="warning" testId="alert-cancel" dismissible>
                  <div className="font-bold">Submission Cancelled</div>
                  <div>You have cancelled the submission. No changes were saved.</div>
                </Alert>
              )}
              {alertDisplay === 'info' && (
                <Alert variant="gray" testId="alert-info" dismissible>
                  <div className="font-bold">Ready to Submit</div>
                  <div>Fill out the form and click Submit to add your new add-on to Seeq.</div>
                </Alert>
              )}
            </div>
          </div>
          {/* ButtonGroup Example: Show and select a display type */}
          <div className="formRow mt-8">
            <div className="labelWidth">ButtonGroup example</div>
            <div className="formElementWidth">
              <ButtonGroup
                buttons={[
                  {
                    variant: 'button',
                    buttonProps: {
                      label: 'Left',
                      value: 'left',
                      variant: 'outline',
                      isActive: btGroupType === 'left',
                    },
                  },
                  {
                    variant: 'button',
                    buttonProps: {
                      label: 'Center',
                      value: 'center',
                      variant: 'outline',
                      isActive: btGroupType === 'center',
                    },
                  },
                  {
                    variant: 'button',
                    buttonProps: {
                      label: 'Right',
                      value: 'right',
                      variant: 'outline',
                      isActive: btGroupType === 'right',
                    },
                  },
                ]}
                onChange={(type) => setBtGroupType(type)}
                extraClassNames="mb-4"
              />
            </div>
          </div>
          {/* Carousel Example: Show a set of images with captions, allow navigation */}
          <div className="formRow mt-8 h-60">
            <div className="labelWidth">Carousel example</div>
            <div className="formElementWidth">
              <Carousel
                carouselItems={[
                  <div className="flex flex-col items-center justify-center p-4" key="slide1">
                    <img
                      src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=400&h=250&q=80"
                      alt="Mountains"
                      className="w-48 h-32 object-cover rounded-md mb-2"
                    />
                    <div className="font-bold">Explore the Mountains</div>
                    <div className="text-xs tw:text-sq-dark-gray">Find peace in nature's beauty.</div>
                  </div>,
                  <div className="flex flex-col items-center justify-center p-4" key="slide2">
                    <img
                      src="https://images.unsplash.com/photo-1465101046530-73398c7f28ca?auto=format&fit=crop&w=400&h=250&q=80"
                      alt="City"
                      className="w-48 h-32 object-cover rounded-md mb-2"
                    />
                    <div className="font-bold">City Lights</div>
                    <div className="text-xs tw:text-sq-dark-gray">Experience the energy of the city.</div>
                  </div>,
                  <div className="flex flex-col items-center justify-center p-4" key="slide3">
                    <img
                      src="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?auto=format&fit=crop&w=400&h=250&q=80"
                      alt="Beach"
                      className="w-48 h-32 object-cover rounded-md mb-2"
                    />
                    <div className="font-bold">Relax at the Beach</div>
                    <div className="text-xs tw:text-sq-dark-gray">Soak up the sun and surf.</div>
                  </div>,
                ]}
                showArrows={false}
                continuous={true}
                showIndicators
                autoSlide={false}
                testId="carousel-example"
                extraClassNames="rounded-md shadow-sm mb-4"
              />
            </div>
          </div>
          {/* Collapse Example: Expand/collapse a section for additional details */}
          <div className="formRow mt-8">
            <div className="labelWidth">Collapse example</div>
            <div className="formElementWidth">
              <Button
                label={collapseVisible ? 'Hide advanced options' : 'Show advanced options'}
                variant="outline"
                onClick={() => setCollapseVisible((v) => !v)}
                extraClassNames="mb-2"
              />
              <Collapse isVisible={collapseVisible}>
                <div className="p-4 mt-2 bg-transparent rounded-md">
                  <div className="font-bold">Advanced Settings</div>
                  <div className="text-xs tw:text-sq-dark-gray">Configure rarely used options here.</div>
                  <Checkbox label="Enable beta features" />
                  <Checkbox label="Show debug info" />
                </div>
              </Collapse>
            </div>
          </div>
          {/* SeeqActionDropdown Example: Contextual actions for a document */}
          <div className="formRow mt-8">
            <div className="labelWidth">SeeqActionDropdown example</div>
            <div className="formElementWidth">
              <SeeqActionDropdown
                seeqActionDropdownItems={[
                  {
                    display: 'Edit Document',
                    icon: 'fc-edit',
                    action: () => alert('Edit action triggered!'),
                    text: 'Edit the selected document',
                    enabled: true,
                  },
                  {
                    display: 'Share',
                    icon: 'fc-share',
                    action: () => alert('Share action triggered!'),
                    text: 'Share the selected document',
                    enabled: true,
                  },
                  {
                    display: 'Delete',
                    icon: 'fc-delete',
                    action: () => alert('Delete action triggered!'),
                    text: 'Delete the selected document',
                    enabled: true,
                  },
                ]}
                trigger={<Button label="Actions" icon="fc-more" variant="outline" extraClassNames="w-32" />}
                variant="create-workbench"
                id="seeq-action-dropdown-example"
              />
            </div>
          </div>
          {/* InputGroup Example: Input with edit and delete icon buttons */}
          <div className="formRow mt-8">
            <div className="labelWidth">InputGroup example</div>
            <div className="formElementWidth">
              <InputGroup
                value={inputGroupValue}
                onChange={(e) => setInputGroupValue(e.target.value)}
                placeholder="Enter item name"
                append={[
                  {
                    variant: 'button',
                    buttonProps: {
                      icon: 'fc-edit',
                      variant: 'outline',
                      onClick: () => setInputGroupValue('Edit clicked'),
                    },
                  },
                  {
                    variant: 'button',
                    buttonProps: {
                      icon: 'fc-delete',
                      variant: 'outline',
                      onClick: () => setInputGroupValue('Delete clicked'),
                    },
                  },
                ]}
                extraClassNames="flex-1"
              />
            </div>
          </div>
          {/* ProgressBar Example: Show progress of a task */}
          <div className="formRow mt-8">
            <div className="labelWidth">ProgressBar example</div>
            <div className="formElementWidth flex flex-col items-start gap-1">
              <ProgressBar
                values={[
                  { value: 85, label: 'Uploading orders', color: '#0491c2' },
                  { value: 90, label: 'Processing invoices', color: '#f59e42' },
                ]}
                max={200}
                containerExtraClasses="w-full"
              />
              <span className="text-xs text-[#0491c2]">Uploading orders... 85%</span>
              <span className="text-xs text-[#f59e42]">Processing invoices... 90%</span>
            </div>
          </div>
          {/* Slider Example: Adjust a value with immediate feedback */}
          <div className="formRow mt-8">
            <div className="labelWidth">Slider example</div>
            <div className="formElementWidth flex items-center gap-4">
              <Slider
                min={0}
                max={100}
                step={5}
                value={sliderValue}
                onValueChange={(val: number[]) => setSliderValue(val[0])}
                rootExtraClassNames="w-64"
              />
              <span className="text-xs text-sq-color-gray">Current value: {sliderValue}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Example;
