'use client'

import { Avatar } from '@/components/avatar'
import { Badge } from '@/components/badge'
import { Divider } from '@/components/divider'
import { Heading, Subheading } from '@/components/heading'
import { Select } from '@/components/select'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/table'
import { getRecentOrders } from '@/data'
import { useEffect, useState } from 'react'
import {
  Dialog,
  DialogPanel,
  Disclosure,
  DisclosureButton,
  DisclosurePanel,
} from '@headlessui/react'
import {
  Bars3Icon,
  MinusSmallIcon,
  PlusSmallIcon,
  XMarkIcon,
} from '@heroicons/react/24/outline'
import {
  ArrowPathIcon,
  CheckIcon,
  CloudArrowUpIcon,
  Cog6ToothIcon,
  FingerPrintIcon,
  LockClosedIcon,
  ServerIcon,
} from '@heroicons/react/20/solid'

type NavigationItem = {
  name: string
  href: string
}

type Feature = {
  name: string
  description: string
  icon: React.ElementType
}

type Tier = {
  name: string
  id: string
  href: string
  priceMonthly: string
  description: string
  features: string[]
  featured: boolean
}

type FAQ = {
  question: string
  answer: string
}

type FooterNavigation = {
  [key: string]: NavigationItem[]
}

type Order = {
  id: string | number
  url: string
  date: string
  customer: { name: string }
  event: { name: string; thumbUrl: string }
  amount: { usd: string }
}


const navigation: NavigationItem[] = [
  { name: 'Product', href: '#' },
  { name: 'Features', href: '#' },
  { name: 'Marketplace', href: '#' },
  { name: 'Company', href: '#' },
]

const features: Feature[] = [
  { name: 'Push to deploy.', description: 'Lorem ipsum...', icon: CloudArrowUpIcon },
  { name: 'SSL certificates.', description: 'Anim aute id...', icon: LockClosedIcon },
  { name: 'Simple queues.', description: 'Ac tincidunt...', icon: ArrowPathIcon },
  { name: 'Advanced security.', description: 'Lorem ipsum...', icon: FingerPrintIcon },
  { name: 'Powerful API.', description: 'Anim aute id...', icon: Cog6ToothIcon },
  { name: 'Database backups.', description: 'Ac tincidunt...', icon: ServerIcon },
];

const tiers: Tier[] = [
  {
    name: 'Hobby',
    id: 'tier-hobby',
    href: '#',
    priceMonthly: '$19',
    description: "The perfect plan if you're just getting started...",
    features: ['25 products', 'Up to 10,000 subscribers', 'Advanced analytics', '24-hour support response time'],
    featured: false,
  },
  {
    name: 'Enterprise',
    id: 'tier-enterprise',
    href: '#',
    priceMonthly: '$49',
    description: 'Dedicated support and infrastructure for your company.',
    features: ['Unlimited products', 'Unlimited subscribers', 'Advanced analytics', 'Dedicated support representative', 'Marketing automations', 'Custom integrations'],
    featured: true,
  },
]

const faqs: FAQ[] = [
  {
    question: "What's the best thing about Switzerland?",
    answer: "I don't know, but the flag is a big plus...",
  },
]

const footerNavigation: FooterNavigation = {
  solutions: [
    { name: 'Marketing', href: '#' },
    { name: 'Analytics', href: '#' },
    { name: 'Automation', href: '#' },
    { name: 'Commerce', href: '#' },
    { name: 'Insights', href: '#' },
  ],
  support: [
    { name: 'Submit ticket', href: '#' },
    { name: 'Documentation', href: '#' },
    { name: 'Guides', href: '#' },
  ],
  company: [
    { name: 'About', href: '#' },
    { name: 'Blog', href: '#' },
    { name: 'Jobs', href: '#' },
    { name: 'Press', href: '#' },
  ],
  legal: [
    { name: 'Terms of services', href: '#' },
    { name: 'Privacy policy', href: '#' },
    { name: 'License', href: '#' },
  ],
}

function classNames(...classes: (string | boolean | undefined)[]): string {
  return classes.filter(Boolean).join(' ')
}

export function Stat({ title, value, change }: { title: string; value: string; change: string }) {
  return (
    <div>
      <Divider />
      <div className="mt-6 text-lg/6 font-medium sm:text-sm/6">{title}</div>
      <div className="mt-3 text-3xl/8 font-semibold sm:text-2xl/8">{value}</div>
      <div className="mt-3 text-sm/6 sm:text-xs/6">
        <Badge color={change.startsWith('+') ? 'lime' : 'pink'}>{change}</Badge>{' '}
        <span className="text-zinc-500">Depuis 1 semaine</span>
      </div>
    </div>
  )
}

export default function Home() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  useEffect(() => {
    const fetchOrders = async () => {
      try {
        const data = await getRecentOrders();
        setOrders(data.map(order => ({ ...order, id: String(order.id) }))); // Conversion de l'ID en chaîne
      } catch (error) {
        console.error('Erreur lors de la récupération des commandes :', error);
      }
    };

    fetchOrders();
  }, []);

  return (
    <>
      <div className="bg-white">
        {/* Header */}
        <header className="absolute inset-x-0 top-0 z-50">
          <nav aria-label="Global" className="flex items-center justify-between p-6 lg:px-8">
            <div className="flex lg:flex-1">
              <a href="#" className="-m-1.5 p-1.5">
                <span className="sr-only">Your Company</span>
                <img
                  alt=""
                  src="https://tailwindui.com/plus/img/logos/mark.svg?color=indigo&shade=500"
                  className="h-8 w-auto"
                />
              </a>
            </div>
            <div className="flex lg:hidden">
              <button
                type="button"
                onClick={() => setMobileMenuOpen(true)}
                className="-m-2.5 inline-flex items-center justify-center rounded-md p-2.5 text-gray-400"
              >
                <span className="sr-only">Open main menu</span>
                <Bars3Icon aria-hidden="true" className="size-6" />
              </button>
            </div>
            <div className="hidden lg:flex lg:gap-x-12">
              {/* Navigation */}
            </div>
          </nav>
        </header>

        <main>
          <Heading>Hello World</Heading>
          <div className="mt-8 flex items-end justify-between">
            <Subheading>Overview</Subheading>
            <div>
              <Select name="period">
                <option value="last_week">Last week</option>
                <option value="last_two">Last two weeks</option>
                <option value="last_month">Last month</option>
                <option value="last_quarter">Last quarter</option>
              </Select>
            </div>
          </div>
          <div className="mt-4 grid gap-8 sm:grid-cols-2 xl:grid-cols-4">
            <Stat title="Total revenue" value="$2.6M" change="+4.5%" />
            <Stat title="Average order value" value="$455" change="-0.5%" />
            <Stat title="Tickets sold" value="5,888" change="+4.5%" />
            <Stat title="Pageviews" value="823,067" change="+21.2%" />
          </div>
          <Subheading className="mt-14">Recent orders</Subheading>
          <Table className="mt-4 [--gutter:theme(spacing.6)] lg:[--gutter:theme(spacing.10)]">
            <TableHead>
              <TableRow>
                <TableHeader>Order number</TableHeader>
                <TableHeader>Purchase date</TableHeader>
                <TableHeader>Customer</TableHeader>
                <TableHeader>Event</TableHeader>
                <TableHeader className="text-right">Amount</TableHeader>
              </TableRow>
            </TableHead>
            <TableBody>
              {orders.map((order) => (
                <TableRow key={order.id} href={order.url} title={`Order #${order.id}`}>
                  <TableCell>{order.id}</TableCell>
                  <TableCell className="text-zinc-500">{order.date}</TableCell>
                  <TableCell>{order.customer.name}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Avatar src={order.event.thumbUrl} className="size-6" />
                      <span>{order.event.name}</span>
                    </div>
                  </TableCell>
                  <TableCell className="text-right">US{order.amount.usd}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </main>
      </div>
    </>
  );
}