import * as icon from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement } from 'react';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';

type BusinessMessage = {
  id: number;
  sender: string;
  text: string;
  time: string;
  mine?: boolean;
};

type SocialPost = {
  id: number;
  author: string;
  text: string;
  tag: string;
  likes: number;
};

type Product = {
  id: number;
  name: string;
  seller: string;
  price: number;
  badge: string;
  stock: number;
};

type CartItem = Product & {
  qty: number;
};

type WalletTransaction = {
  id: number;
  label: string;
  amount: number;
  type: 'in' | 'out';
  note: string;
};

type Activity = {
  id: number;
  module: string;
  text: string;
  time: string;
};

const fallbackIcon = icon.mdiViewDashboardOutline;
const resolveIcon = (name: string) =>
  (name in icon ? icon[name as keyof typeof icon] : fallbackIcon) as string;

const formatCurrency = (value: number) =>
  new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency: 'IDR',
    maximumFractionDigits: 0,
  }).format(value);

const MegaSuperAppPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const iconsColor = useAppSelector((state) => state.style.iconsColor);

  const [activeConversation, setActiveConversation] = React.useState('Mitra Grosir Bandung');
  const [messageInput, setMessageInput] = React.useState('');
  const [postInput, setPostInput] = React.useState('');
  const [walletInput, setWalletInput] = React.useState('25000');
  const [walletNote, setWalletNote] = React.useState('Top up saldo operasional');
  const [balance, setBalance] = React.useState(1250000);

  const [messages, setMessages] = React.useState<BusinessMessage[]>([
    {
      id: 1,
      sender: 'Mitra Grosir Bandung',
      text: 'Stok paket reseller sudah siap. Mau langsung dibuatkan invoice marketplace?',
      time: '09:12',
    },
    {
      id: 2,
      sender: 'Anda',
      text: 'Ya, kirim 12 paket. Pembayaran saya pakai dompet workspace.',
      time: '09:15',
      mine: true,
    },
    {
      id: 3,
      sender: 'Mitra Grosir Bandung',
      text: 'Siap. Saya tautkan order ke chat ini supaya tracking reputasi ikut naik.',
      time: '09:17',
    },
  ]);

  const [posts, setPosts] = React.useState<SocialPost[]>([
    {
      id: 1,
      author: 'Komunitas Seller Lokal',
      text: 'Promo bareng akhir pekan: bundling produk komunitas, cashback dompet, dan diskusi live di feed.',
      tag: 'Kolaborasi',
      likes: 42,
    },
    {
      id: 2,
      author: 'Rina Kopi Nusantara',
      text: 'Baru upload katalog kopi 250gr. Pembeli dari chat bisnis bisa checkout tanpa pindah aplikasi.',
      tag: 'Marketplace',
      likes: 27,
    },
  ]);

  const products: Product[] = [
    {
      id: 1,
      name: 'Paket Reseller Kopi 12 pcs',
      seller: 'Kopi Nusantara',
      price: 360000,
      badge: 'Terhubung chat',
      stock: 18,
    },
    {
      id: 2,
      name: 'Voucher Iklan Feed Komunitas',
      seller: '01 Ads Lite',
      price: 150000,
      badge: 'Naikkan reputasi',
      stock: 40,
    },
    {
      id: 3,
      name: 'Jasa Desain Katalog UMKM',
      seller: 'Studio Pasar Sosial',
      price: 275000,
      badge: 'Escrow dompet',
      stock: 7,
    },
  ];

  const [cart, setCart] = React.useState<CartItem[]>([
    { ...products[0], qty: 1 },
  ]);

  const [transactions, setTransactions] = React.useState<WalletTransaction[]>([
    {
      id: 1,
      label: 'Pembayaran order kopi',
      amount: 360000,
      type: 'out',
      note: 'Marketplace • escrow aktif',
    },
    {
      id: 2,
      label: 'Cashback komunitas seller',
      amount: 50000,
      type: 'in',
      note: 'Reward sosial',
    },
    {
      id: 3,
      label: 'Top up dompet',
      amount: 500000,
      type: 'in',
      note: 'Bank transfer',
    },
  ]);

  const [activities, setActivities] = React.useState<Activity[]>([
    {
      id: 1,
      module: 'Chat',
      text: 'Negosiasi dengan Mitra Grosir Bandung ditautkan ke order #MSA-1201.',
      time: 'Baru saja',
    },
    {
      id: 2,
      module: 'Marketplace',
      text: '1 produk masuk keranjang dan siap dibayar dari Dompet 01.',
      time: '3 menit lalu',
    },
    {
      id: 3,
      module: 'Sosial',
      text: 'Posting komunitas seller mendapat 42 suka dan 8 calon pembeli.',
      time: '12 menit lalu',
    },
  ]);

  const userName = currentUser?.firstName || currentUser?.email || 'Pengguna 01';
  const cartTotal = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
  const projectedBalance = balance - cartTotal;

  const addActivity = (module: string, text: string) => {
    setActivities((current) => [
      {
        id: Date.now(),
        module,
        text,
        time: 'Baru saja',
      },
      ...current.slice(0, 5),
    ]);
  };

  const sendMessage = () => {
    const trimmed = messageInput.trim();

    if (!trimmed) {
      return;
    }

    setMessages((current) => [
      ...current,
      {
        id: Date.now(),
        sender: 'Anda',
        text: trimmed,
        time: 'Sekarang',
        mine: true,
      },
    ]);
    setMessageInput('');
    addActivity('Chat', `Pesan bisnis baru dikirim ke ${activeConversation}.`);
  };

  const publishPost = () => {
    const trimmed = postInput.trim();

    if (!trimmed) {
      return;
    }

    setPosts((current) => [
      {
        id: Date.now(),
        author: String(userName),
        text: trimmed,
        tag: 'Update Bisnis',
        likes: 0,
      },
      ...current,
    ]);
    setPostInput('');
    addActivity('Sosial', 'Update baru diterbitkan ke feed komunitas.');
  };

  const addToCart = (product: Product) => {
    setCart((current) => {
      const existing = current.find((item) => item.id === product.id);

      if (existing) {
        return current.map((item) =>
          item.id === product.id ? { ...item, qty: item.qty + 1 } : item,
        );
      }

      return [...current, { ...product, qty: 1 }];
    });
    addActivity('Marketplace', `${product.name} ditambahkan ke keranjang terpadu.`);
  };

  const checkoutCart = () => {
    if (!cart.length || cartTotal > balance) {
      return;
    }

    setBalance((current) => current - cartTotal);
    setTransactions((current) => [
      {
        id: Date.now(),
        label: 'Checkout marketplace terpadu',
        amount: cartTotal,
        type: 'out',
        note: `${cart.length} item • escrow dompet`,
      },
      ...current,
    ]);
    setCart([]);
    addActivity('Dompet', `Checkout ${formatCurrency(cartTotal)} berhasil memakai Dompet 01.`);
  };

  const addWalletTransaction = () => {
    const amount = Number(walletInput);
    const trimmedNote = walletNote.trim() || 'Top up dompet workspace';

    if (!amount || amount <= 0) {
      return;
    }

    setBalance((current) => current + amount);
    setTransactions((current) => [
      {
        id: Date.now(),
        label: 'Top up cepat',
        amount,
        type: 'in',
        note: trimmedNote,
      },
      ...current,
    ]);
    setWalletInput('');
    setWalletNote('');
    addActivity('Dompet', `Saldo bertambah ${formatCurrency(amount)} dari top up cepat.`);
  };

  const conversations = [
    {
      name: 'Mitra Grosir Bandung',
      status: 'Invoice marketplace siap',
      unread: 2,
    },
    {
      name: 'Komunitas Seller Lokal',
      status: 'Diskusi promo bareng',
      unread: 4,
    },
    {
      name: 'Customer Prioritas',
      status: 'Butuh update pengiriman',
      unread: 1,
    },
  ];

  return (
    <>
      <Head>
        <title>{getPageTitle('3. Mega Super-App')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={resolveIcon('mdiApps')}
          title="3. Mega Super-App"
          main
        >
          <BaseButton
            href="/vorta-commerce"
            icon={icon.mdiViewDashboardOutline}
            label="Kembali ke Dasbor"
            color="whiteDark"
          />
        </SectionTitleLineWithButton>

        <CardBox className="mb-6 overflow-hidden" hasComponentLayout>
          <div className="grid grid-cols-1 gap-0 lg:grid-cols-5">
            <div className="p-6 lg:col-span-3">
              <div className="mb-3 inline-flex items-center rounded-full bg-blue-50 px-3 py-1 text-sm font-semibold text-blue-700 dark:bg-blue-900/30 dark:text-blue-200">
                <BaseIcon path={resolveIcon('mdiFlashOutline')} className="mr-2" size={18} />
                3. Mega Super-App · Chat Bisnis, Sosial, Marketplace, Dan Dompet Dalam Satu Ruang Kerja Ringan
              </div>
              <h2 className="mb-3 text-3xl font-bold leading-tight md:text-4xl">
                Halo {userName}, kelola semua aktivitas dari satu ruang kerja.
              </h2>
              <p className="mb-5 max-w-3xl text-gray-600 dark:text-gray-300">
                MVP ini menyatukan chat bisnis, feed komunitas, katalog marketplace,
                keranjang, pembayaran dompet, dan aktivitas terpadu tanpa pindah halaman.
              </p>
              <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
                {[
                  { label: 'Chat aktif', value: conversations.length, iconName: 'mdiChatProcessingOutline' },
                  { label: 'Posting sosial', value: posts.length, iconName: 'mdiPostOutline' },
                  { label: 'Produk live', value: products.length, iconName: 'mdiStorefrontOutline' },
                  { label: 'Saldo dompet', value: formatCurrency(balance), iconName: 'mdiWalletOutline' },
                ].map((item) => (
                  <div
                    key={item.label}
                    className="rounded-2xl border border-gray-100 bg-white/70 p-4 shadow-sm dark:border-dark-700 dark:bg-dark-800/60"
                  >
                    <BaseIcon path={resolveIcon(item.iconName)} className={`${iconsColor} mb-3`} size={26} />
                    <div className="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">
                      {item.label}
                    </div>
                    <div className="mt-1 text-xl font-bold">{item.value}</div>
                  </div>
                ))}
              </div>
            </div>
            <div className="border-t border-gray-100 bg-gray-50 p-6 dark:border-dark-700 dark:bg-dark-800/70 lg:col-span-2 lg:border-l lg:border-t-0">
              <div className="mb-4 flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">Status workspace</p>
                  <h3 className="text-xl font-semibold">Siap operasional</h3>
                </div>
                <span className="rounded-full bg-green-100 px-3 py-1 text-sm font-semibold text-green-700 dark:bg-green-900/30 dark:text-green-200">
                  Live MVP
                </span>
              </div>
              <div className="space-y-3">
                {activities.slice(0, 4).map((activity) => (
                  <div key={activity.id} className="rounded-xl bg-white p-3 dark:bg-dark-900">
                    <div className="mb-1 flex items-center justify-between text-sm">
                      <span className="font-semibold text-blue-700 dark:text-blue-300">{activity.module}</span>
                      <span className="text-gray-400">{activity.time}</span>
                    </div>
                    <p className="text-sm text-gray-600 dark:text-gray-300">{activity.text}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </CardBox>

        <div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
          <CardBox className="xl:col-span-2" hasComponentLayout>
            <div className="grid min-h-[620px] grid-cols-1 lg:grid-cols-5">
              <aside className="border-b border-gray-100 p-4 dark:border-dark-700 lg:col-span-2 lg:border-b-0 lg:border-r">
                <div className="mb-4 flex items-center justify-between">
                  <div>
                    <h3 className="text-xl font-semibold">Chat Bisnis</h3>
                    <p className="text-sm text-gray-500 dark:text-gray-400">Percakapan, order, dan dompet tersambung.</p>
                  </div>
                  <BaseIcon path={resolveIcon('mdiChat')} className={iconsColor} size={30} />
                </div>
                <div className="space-y-3">
                  {conversations.map((conversation) => (
                    <button
                      key={conversation.name}
                      type="button"
                      onClick={() => setActiveConversation(conversation.name)}
                      className={`w-full rounded-2xl border p-3 text-left transition ${
                        activeConversation === conversation.name
                          ? 'border-blue-300 bg-blue-50 dark:border-blue-800 dark:bg-blue-900/20'
                          : 'border-gray-100 bg-white hover:border-blue-200 dark:border-dark-700 dark:bg-dark-900'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <span className="font-semibold">{conversation.name}</span>
                        <span className="rounded-full bg-orange-100 px-2 py-0.5 text-xs font-bold text-orange-700 dark:bg-orange-900/30 dark:text-orange-200">
                          {conversation.unread}
                        </span>
                      </div>
                      <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">{conversation.status}</p>
                    </button>
                  ))}
                </div>

                <div className="mt-5 rounded-2xl bg-gray-50 p-4 dark:bg-dark-800">
                  <p className="mb-2 text-sm font-semibold text-gray-600 dark:text-gray-300">Aksi cepat</p>
                  <div className="grid grid-cols-2 gap-2">
                    <BaseButton label="Buat Order" icon={resolveIcon('mdiReceiptTextPlusOutline')} color="info" small />
                    <BaseButton label="Kirim Invoice" icon={resolveIcon('mdiFileSendOutline')} color="success" small />
                  </div>
                </div>
              </aside>

              <section className="flex flex-col lg:col-span-3">
                <div className="border-b border-gray-100 p-4 dark:border-dark-700">
                  <p className="text-sm text-gray-500 dark:text-gray-400">Ruang chat aktif</p>
                  <h3 className="text-xl font-semibold">{activeConversation}</h3>
                </div>
                <div className="flex-1 space-y-3 bg-gray-50 p-4 dark:bg-dark-800/50">
                  {messages.map((message) => (
                    <div key={message.id} className={`flex ${message.mine ? 'justify-end' : 'justify-start'}`}>
                      <div
                        className={`max-w-[82%] rounded-2xl px-4 py-3 shadow-sm ${
                          message.mine
                            ? 'bg-blue-600 text-white'
                            : 'bg-white text-gray-800 dark:bg-dark-900 dark:text-gray-100'
                        }`}
                      >
                        <div className={`mb-1 text-xs ${message.mine ? 'text-blue-100' : 'text-gray-400'}`}>
                          {message.sender} • {message.time}
                        </div>
                        <p className="text-sm leading-relaxed">{message.text}</p>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="border-t border-gray-100 p-4 dark:border-dark-700">
                  <div className="flex gap-2">
                    <input
                      value={messageInput}
                      onChange={(event) => setMessageInput(event.target.value)}
                      onKeyDown={(event) => {
                        if (event.key === 'Enter') {
                          sendMessage();
                        }
                      }}
                      className="h-11 flex-1 rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-blue-400 focus:ring dark:border-dark-700 dark:bg-dark-900"
                      placeholder="Tulis pesan, buat invoice, atau tautkan produk..."
                    />
                    <BaseButton label="Kirim" icon={resolveIcon('mdiSend')} color="info" onClick={sendMessage} />
                  </div>
                </div>
              </section>
            </div>
          </CardBox>

          <div className="space-y-6">
            <CardBox hasComponentLayout>
              <div className="p-5">
                <div className="mb-4 flex items-center justify-between">
                  <div>
                    <h3 className="text-xl font-semibold">Dompet 01</h3>
                    <p className="text-sm text-gray-500 dark:text-gray-400">Saldo, top up, checkout, dan escrow.</p>
                  </div>
                  <BaseIcon path={resolveIcon('mdiWalletOutline')} className={iconsColor} size={32} />
                </div>
                <div className="rounded-3xl bg-gradient-to-br from-blue-600 to-emerald-500 p-5 text-white shadow-lg">
                  <p className="text-sm opacity-80">Saldo tersedia</p>
                  <div className="mt-1 text-3xl font-bold">{formatCurrency(balance)}</div>
                  <p className="mt-3 text-sm opacity-90">Estimasi setelah checkout: {formatCurrency(projectedBalance)}</p>
                </div>
                <div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-2">
                  <input
                    value={walletInput}
                    onChange={(event) => setWalletInput(event.target.value)}
                    type="number"
                    min="0"
                    className="h-10 rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-blue-400 focus:ring dark:border-dark-700 dark:bg-dark-900"
                    placeholder="Nominal top up"
                  />
                  <input
                    value={walletNote}
                    onChange={(event) => setWalletNote(event.target.value)}
                    className="h-10 rounded-xl border border-gray-200 bg-white px-3 text-sm outline-none focus:border-blue-400 focus:ring dark:border-dark-700 dark:bg-dark-900"
                    placeholder="Catatan"
                  />
                </div>
                <BaseButton
                  label="Top Up Cepat"
                  icon={resolveIcon('mdiPlusCircleOutline')}
                  color="success"
                  className="mt-3 w-full"
                  onClick={addWalletTransaction}
                />
                <div className="mt-5 space-y-3">
                  {transactions.slice(0, 4).map((transaction) => (
                    <div key={transaction.id} className="flex items-start justify-between rounded-2xl bg-gray-50 p-3 dark:bg-dark-800">
                      <div>
                        <p className="font-semibold">{transaction.label}</p>
                        <p className="text-sm text-gray-500 dark:text-gray-400">{transaction.note}</p>
                      </div>
                      <span className={`font-bold ${transaction.type === 'in' ? 'text-green-600' : 'text-red-500'}`}>
                        {transaction.type === 'in' ? '+' : '-'}{formatCurrency(transaction.amount)}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            </CardBox>
          </div>
        </div>

        <div className="mt-6 grid grid-cols-1 gap-6 xl:grid-cols-2">
          <CardBox hasComponentLayout>
            <div className="p-5">
              <div className="mb-4 flex items-center justify-between">
                <div>
                  <h3 className="text-xl font-semibold">Feed Sosial Bisnis</h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400">Bangun komunitas dan reputasi sambil menjual.</p>
                </div>
                <BaseIcon path={resolveIcon('mdiAccountVoice')} className={iconsColor} size={32} />
              </div>
              <textarea
                value={postInput}
                onChange={(event) => setPostInput(event.target.value)}
                className="h-24 w-full rounded-2xl border border-gray-200 bg-white p-3 text-sm outline-none focus:border-blue-400 focus:ring dark:border-dark-700 dark:bg-dark-900"
                placeholder="Tulis update komunitas, promo sosial, atau cerita pelanggan..."
              />
              <div className="mt-3 flex justify-end">
                <BaseButton label="Posting ke Feed" icon={resolveIcon('mdiPostOutline')} color="info" onClick={publishPost} />
              </div>
              <div className="mt-5 space-y-4">
                {posts.map((post) => (
                  <div key={post.id} className="rounded-2xl border border-gray-100 p-4 dark:border-dark-700">
                    <div className="mb-2 flex items-center justify-between">
                      <div>
                        <p className="font-semibold">{post.author}</p>
                        <span className="text-xs font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-300">{post.tag}</span>
                      </div>
                      <span className="inline-flex items-center rounded-full bg-gray-50 px-3 py-1 text-sm dark:bg-dark-800">
                        <BaseIcon path={resolveIcon('mdiHeartOutline')} className="mr-1 text-red-500" size={16} />
                        {post.likes}
                      </span>
                    </div>
                    <p className="text-gray-600 dark:text-gray-300">{post.text}</p>
                  </div>
                ))}
              </div>
            </div>
          </CardBox>

          <CardBox hasComponentLayout>
            <div className="p-5">
              <div className="mb-4 flex items-center justify-between">
                <div>
                  <h3 className="text-xl font-semibold">Marketplace Ringan</h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400">Produk, chat seller, keranjang, dan pembayaran dompet.</p>
                </div>
                <BaseIcon path={resolveIcon('mdiStorefrontOutline')} className={iconsColor} size={32} />
              </div>
              <div className="grid grid-cols-1 gap-4 lg:grid-cols-3 xl:grid-cols-1 2xl:grid-cols-3">
                {products.map((product) => (
                  <div key={product.id} className="rounded-2xl border border-gray-100 p-4 dark:border-dark-700">
                    <span className="mb-3 inline-flex rounded-full bg-orange-50 px-3 py-1 text-xs font-bold text-orange-700 dark:bg-orange-900/30 dark:text-orange-200">
                      {product.badge}
                    </span>
                    <h4 className="min-h-[48px] font-semibold">{product.name}</h4>
                    <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">{product.seller} • Stok {product.stock}</p>
                    <div className="mt-3 text-xl font-bold">{formatCurrency(product.price)}</div>
                    <BaseButton
                      label="Tambah"
                      icon={resolveIcon('mdiCartPlus')}
                      color="success"
                      small
                      className="mt-3 w-full"
                      onClick={() => addToCart(product)}
                    />
                  </div>
                ))}
              </div>

              <div className="mt-5 rounded-3xl bg-gray-50 p-4 dark:bg-dark-800">
                <div className="mb-3 flex items-center justify-between">
                  <h4 className="font-semibold">Keranjang Terpadu</h4>
                  <span className="text-sm text-gray-500 dark:text-gray-400">{cart.length} item</span>
                </div>
                {cart.length ? (
                  <div className="space-y-2">
                    {cart.map((item) => (
                      <div key={item.id} className="flex items-center justify-between text-sm">
                        <span>{item.name} × {item.qty}</span>
                        <span className="font-semibold">{formatCurrency(item.price * item.qty)}</span>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-gray-500 dark:text-gray-400">Keranjang kosong. Tambahkan produk untuk checkout.</p>
                )}
                <div className="mt-4 flex items-center justify-between border-t border-gray-200 pt-3 dark:border-dark-700">
                  <span className="font-semibold">Total</span>
                  <span className="text-xl font-bold">{formatCurrency(cartTotal)}</span>
                </div>
                <BaseButton
                  label={cartTotal > balance ? 'Saldo Tidak Cukup' : 'Bayar dari Dompet'}
                  icon={resolveIcon('mdiWalletPlusOutline')}
                  color={cartTotal > balance ? 'danger' : 'info'}
                  disabled={!cart.length || cartTotal > balance}
                  className="mt-3 w-full"
                  onClick={checkoutCart}
                />
              </div>
            </div>
          </CardBox>
        </div>
      </SectionMain>
    </>
  );
};

MegaSuperAppPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default MegaSuperAppPage;
