'use client';
import React, { useRef, useState, useEffect } from 'react';
import { addDays, format } from 'date-fns';
import { CalendarIcon, ChevronsUpDown, Check } from 'lucide-react';
import Link from 'next/link';
import { cn } from '@/lib/utils';
import { Calendar } from '@/components/ui/calendar';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
  DropdownMenuItem,
} from '@/components/ui/dropdown-menu';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Button } from '@/components/ui/button';
import { Text } from '@/components/ui/text';
import { Skeleton } from '@/components/ui/skeleton';
// import WorkspaceView from './WorkspaceView';
import WorkspaceEdit from './WorkspaceEdit';
import WorkspaceAdd from './WorkspaceAdd';
import type { DateRange } from 'react-day-picker';
const frameworks = [
  { value: 'Reminders', label: 'Reminders' },
  { value: 'General Tasks', label: 'General Tasks' },
  { value: 'Personal Notes', label: 'Personal Notes' },
  { value: 'Visa Tasks', label: 'Visa Tasks' },
];
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
} from '@/components/ui/card';
import CommonImage from '@/components/common/CommonImage';
import WorkspaceView from './WorkspaceView';
const WorkSpace: React.FC = () => {
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState('');
  const [activeRow, setActiveRow] = useState<number | null>(null);
  const [tooltipPosition, setTooltipPosition] = useState({
    top: '30%',
    left: '40%',
  });
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [viewDialogOpen, setViewDialogOpen] = useState(false);
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [loading, setLoading] = useState(true); // NEW: loading state
  const containerRef = useRef<HTMLDivElement>(null);
  const tooltipRef = useRef<HTMLDivElement>(null);
  const initialRange: DateRange = {
    from: new Date(2022, 0, 20),
    to: addDays(new Date(2022, 0, 20), 20),
  };
  const [dateRange, setDateRange] = useState<DateRange | undefined>(
    initialRange,
  );
  const [selectedRange, setSelectedRange] = useState<DateRange | undefined>(
    initialRange,
  );
  // Simulate loading
  useEffect(() => {
    const timer = setTimeout(() => setLoading(false), 1000); // simulate 1s delay
    return () => clearTimeout(timer);
  }, []);
  const workspaceItems = [
    {
      Sr: 1,
      title: 'WS00005 - First Task Title',
      desc: 'This is the first task description for workspace.',
      date: '21-04-2025 05:22 PM',
    },
    {
      Sr: 2,
      title: 'WS00006 - Second Task Title',
      desc: 'Another task here, with more information.',
      date: '22-04-2025 10:15 AM',
    },
    {
      Sr: 3,
      title: 'WS00007 - Third Task Entry',
      desc: 'Details about the third task in this list.',
      date: '23-04-2025 01:42 PM',
    },
    {
      Sr: 4,
      title: 'WS00007 - Third Task Entry',
      desc: 'Details about the third task in this list.',
      date: '23-04-2025 01:42 PM',
    },
    {
      Sr: 5,
      title: 'WS00007 - Third Task Entry',
      desc: 'Details about the third task in this list.',
      date: '23-04-2025 01:42 PM',
    },
  ];
  const handleRowClick = (
    e: React.MouseEvent<HTMLDivElement>,
    item: (typeof workspaceItems)[0],
  ) => {
    const container = containerRef.current;
    const target = e.currentTarget;
    if (container) {
      const containerRect = container.getBoundingClientRect();
      const targetRect = target.getBoundingClientRect();
      const offsetTop = targetRect.top - containerRect.top;
      const offsetLeft = targetRect.left - containerRect.left;
      setActiveRow(item.Sr);
      setTooltipPosition({
        top: `${offsetTop + 10}px`,
        left: `${offsetLeft + 200}px`,
      });
    }
  };
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        tooltipRef.current &&
        !tooltipRef.current.contains(event.target as Node)
      ) {
        setActiveRow(null);
      }
    };
    if (activeRow !== null) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
  }, [activeRow]);
  return (
    <Text>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Text className="mt workspace-icon">
            <CommonImage
              src="/header/work-space.webp"
              classname="icon"
              alt=""
              width={20}
              height={20}
            />
          </Text>
        </DropdownMenuTrigger>
        <DropdownMenuContent
          className="w-96 p-4 pb-2 pt-2 workspace-container relative"
          ref={containerRef}
        >
          <Text className="workspace-header flex justify-between pb-2 items-center">
            <Text className="heading">My Workspace</Text>
            <Text className="flex gap-2 create-btn-outer">
              <Button
                className="create-btn"
                onClick={(e) => {
                  e.stopPropagation();
                  setActiveRow(null);
                  setTimeout(() => setAddDialogOpen(true), 0);
                }}
              >
                Create
              </Button>
              <DropdownMenuItem asChild>
                <Button
                  className="cursor-pointer mt-1 workspace-close-icon-btn"
                  variant="ghost"
                  size="sm"
                >
                  <CommonImage
                    src="/main/cross-arrow.webp"
                    classname="close-icon"
                    alt="Close"
                    width={12}
                    height={12}
                  />
                </Button>
              </DropdownMenuItem>
            </Text>
          </Text>
          {/* Filter + Calendar UI (unchanged) */}
          <Text className="flex justify-between pb-2 items-center mt-2 workspace-secondary-header mb-4">
            <Text>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    className="w-[200px] justify-between select-tab-list overflow-hidden"
                  >
                    {value
                      ? frameworks.find((f) => f.value === value)?.label
                      : 'Personal Notes'}

                    <div className="tag-count">1</div>
                    <CommonImage
                      src="/main/tab-down-arrow.webp"
                      classname="tab-down-icon"
                      alt="tab down arrow"
                      width={10}
                      height={10}
                    />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[200px] p-0 workspace-tab-list-widget">
                  <Command>
                    <CommandList>
                      <CommandEmpty>No framework found.</CommandEmpty>
                      <CommandGroup className="table-tab-data">
                        {frameworks.map((framework) => (
                          <CommandItem
                            key={framework.value}
                            value={framework.value}
                            onSelect={(currentValue) => {
                              setValue(
                                currentValue === value ? '' : currentValue,
                              );
                            }}
                          >
                            {framework.label}
                            <Check
                              className={cn(
                                'ml-auto',
                                value === framework.value
                                  ? 'opacity-100'
                                  : 'opacity-0',
                              )}
                            />
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
            </Text>
            <Text>
              <Popover open={open} onOpenChange={setOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className="w-[100%] justify-start text-left font-normal calendar-filter-outer"
                  >
                    <CommonImage
                      src="/main/calendar_filter-icon.webp"
                      width={15}
                      height={15}
                      alt="calendar filter icon"
                      classname="calendar-filter-icon"
                    />
                    {/* {dateRange?.from ? (
                      dateRange.to ? (
                        <>
                          {format(dateRange.from, 'LLL dd, y')} -{' '}
                          {format(dateRange.to, 'LLL dd, y')}
                        </>
                      ) : (
                        format(dateRange.from, 'LLL dd, y')
                      )
                    ) : (
                      <span>Pick a date range</span>
                    )} */}
                  </Button>
                </PopoverTrigger>
                <PopoverContent
                  className="w-auto p-4 space-y-2  calendar-date-widget"
                  align="start"
                >
                  <Calendar
                    initialFocus
                    mode="range"
                    defaultMonth={selectedRange?.from}
                    selected={selectedRange}
                    numberOfMonths={2}
                    onSelect={setSelectedRange} // Works with DateRange type
                  />
                  <div className="flex justify-end gap-2 pt-2">
                    <Button
                      size="sm"
                      onClick={() => {
                        setDateRange(selectedRange);
                        setOpen(false); // Closes the calendar popover
                      }}
                      disabled={!selectedRange?.from}
                      className="calendar-apply-btn"
                    >
                      Apply
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => setSelectedRange(undefined)}
                      className="calendar-clear-btn"
                    >
                      Clear
                    </Button>
                  </div>
                </PopoverContent>
              </Popover>
            </Text>
          </Text>
          {/* ... your tab filter and date picker code remains unchanged */}
          <Text className="middle-workspace relative scrl-y">
            {loading ? (
              <>
                {[...Array(7)].map((_, idx) => (
                  <Skeleton
                    key={idx}
                    className="h-[100px] w-full rounded-xl mb-4"
                  />
                ))}
              </>
            ) : (
              workspaceItems.map((item) => (
                <Card
                  key={item.Sr}
                  className="rounded-none workspace-tab mb-4 cursor-pointer relative pt-1 pb-1 pr-1 pl-1 pt-1"
                  onClick={(e) =>
                    handleRowClick(e as React.MouseEvent<HTMLDivElement>, item)
                  }
                >
                  <CardHeader className="heading pl-1 pr-1 pt-0 pb-0">
                    {item.title}
                  </CardHeader>
                  <CardContent className="space-y-2 description-data pt-1 pb-0 pl-1">
                    {item.desc}
                  </CardContent>
                  <CardFooter className="flex justify-end p-2 pb-0 pt-0 m-0">
                    <Text className="date-time p-0 pb-0 mp-0">{item.date}</Text>
                  </CardFooter>
                  {activeRow === item.Sr && (
                    <div
                      className="absolute z-10 bg-white shadow-md p-2 flex gap-2 rounded-md tooltip-workspace-action"
                      ref={tooltipRef}
                      style={{
                        top: tooltipPosition.top,
                        left: tooltipPosition.left,
                      }}
                    >
                      <Text className="emp-workspace-btns-cont flex gap-2">
                        <Text
                          className="workspace-cross-btn cursor-pointer"
                          onClick={(e) => {
                            e.stopPropagation();
                            setActiveRow(null);
                          }}
                        >
                          <CommonImage
                            src="/main/cross-arrow.webp"
                            classname="icon close-arrow"
                            alt="close"
                            width={14}
                            height={14}
                          />
                        </Text>
                        <Button
                          type="button"
                          variant="ghost"
                          className="p-0 workspace-icons work-edit"
                          onClick={(e) => {
                            e.stopPropagation();
                            setActiveRow(null);
                            setTimeout(() => setEditDialogOpen(true), 0);
                          }}
                        >
                          <CommonImage
                            src="/main/edit-icon.webp"
                            classname="icon edit-icon"
                            alt="edit"
                            width={14}
                            height={14}
                          />
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          className="p-0 workspace-icons work-view"
                          onClick={(e) => {
                            e.stopPropagation();
                            setActiveRow(null);
                            setTimeout(() => setViewDialogOpen(true), 0);
                          }}
                        >
                          <CommonImage
                            src="/main/pass-show.webp"
                            classname="icon view-icon"
                            alt="view"
                            width={18}
                            height={18}
                          />
                        </Button>
                      </Text>
                    </div>
                  )}
                </Card>
              ))
            )}
          </Text>
          <Text className="view-more text-center pt-2 pb-1">
            <Link href="#" className="view-more">
              <b>View More</b>
            </Link>
          </Text>
        </DropdownMenuContent>
      </DropdownMenu>
      {/* Dialog Components */}
      <WorkspaceEdit open={editDialogOpen} onOpenChange={setEditDialogOpen} />
      <WorkspaceView open={viewDialogOpen} onOpenChange={setViewDialogOpen} />
      <WorkspaceAdd open={addDialogOpen} onOpenChange={setAddDialogOpen} />
    </Text>
  );
};
export default WorkSpace;
