'use client';

import {useState} from 'react';
import {proportional, pixel} from '@astryxdesign/core/Table';
import {ResponsiveTable} from '@/shared/components/patterns/ResponsiveTable';
import type {TableColumn} from '@astryxdesign/core/Table';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text, Heading} from '@astryxdesign/core/Text';
import {Badge} from '@astryxdesign/core/Badge';
import {Button} from '@astryxdesign/core/Button';
import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
import {Icon} from '@astryxdesign/core/Icon';
import {TextInput} from '@astryxdesign/core/TextInput';
import {Selector} from '@astryxdesign/core/Selector';
import {useToast} from '@astryxdesign/core/Toast';
import {StaticPanel} from '@/shared/components/patterns/PanelCard';

export interface StoreItem extends Record<string, unknown> {
  id: string;
  name: string;
  location: string;
  manager: string;
  staffCount: number;
  hours: string;
  status: 'active' | 'maintenance' | 'disabled';
}

const INITIAL_STORES: StoreItem[] = [
  {
    id: 'blr-indiranagar',
    name: 'Indiranagar Flagship',
    location: '100 Feet Road, Indiranagar, Bengaluru',
    manager: 'Vikram Seth',
    staffCount: 14,
    hours: '08:00 – 23:00',
    status: 'active',
  },
  {
    id: 'blr-koramangala',
    name: 'Koramangala 80ft',
    location: '80 Feet Road, Koramangala 4th Block, Bengaluru',
    manager: 'Priya Sharma',
    staffCount: 9,
    hours: '09:00 – 22:30',
    status: 'active',
  },
  {
    id: 'blr-whitefield',
    name: 'Whitefield Main',
    location: 'ITPL Main Road, Whitefield, Bengaluru',
    manager: 'Deepa Nair',
    staffCount: 6,
    hours: '10:00 – 22:00',
    status: 'maintenance',
  },
  {
    id: 'blr-jayanagar',
    name: 'Jayanagar 4th Block',
    location: '11th Main Rd, Jayanagar, Bengaluru',
    manager: 'Suresh T',
    staffCount: 8,
    hours: '09:00 – 21:30',
    status: 'active',
  },
  {
    id: 'blr-mgroad',
    name: 'MG Road Express',
    location: 'Church Street, Off MG Road, Bengaluru',
    manager: 'Unassigned',
    staffCount: 0,
    hours: '10:00 – 21:00',
    status: 'disabled',
  },
];

export function StoreManagement() {
  const toast = useToast();
  const [stores, setStores] = useState<StoreItem[]>(INITIAL_STORES);
  const [isAdding, setIsAdding] = useState(false);
  const [name, setName] = useState('');
  const [location, setLocation] = useState('');
  const [manager, setManager] = useState('Vikram Seth');
  const [hours, setHours] = useState('09:00 – 22:00');

  const handleAddStore = () => {
    if (!name.trim()) {
      toast({type: 'error', body: 'Store name is required'});
      return;
    }
    const newStore: StoreItem = {
      id: `blr-${name.toLowerCase().replace(/\s+/g, '')}`,
      name,
      location: location || 'Bengaluru, Karnataka',
      manager,
      staffCount: 1,
      hours,
      status: 'active',
    };
    setStores((prev) => [newStore, ...prev]);
    setName('');
    setLocation('');
    setIsAdding(false);
    toast({body: `Store "${name}" added successfully`});
  };

  const handleToggleStatus = (id: string) => {
    setStores((prev) =>
      prev.map((s) => {
        if (s.id !== id) return s;
        const next = s.status === 'active' ? 'disabled' : 'active';
        toast({body: `${s.name} status updated to ${next}`});
        return {...s, status: next};
      }),
    );
  };

  const handleRemove = (id: string, storeName: string) => {
    setStores((prev) => prev.filter((s) => s.id !== id));
    toast({body: `Store "${storeName}" removed`});
  };

  const columns: TableColumn<StoreItem>[] = [
    {
      key: 'name',
      header: 'Store Location',
      width: proportional(2),
      renderCell: (row) => (
        <VStack gap={0}>
          <Text size="sm" weight="medium">
            {row.name}
          </Text>
          <Text size="sm" color="secondary">
            {row.location}
          </Text>
        </VStack>
      ),
    },
    {
      key: 'manager',
      header: 'Store Manager',
      width: proportional(1.2),
      renderCell: (row) => <Text size="sm">{row.manager}</Text>,
    },
    {
      key: 'hours',
      header: 'Operating Hours',
      width: proportional(1.2),
      renderCell: (row) => (
        <Text size="sm" color="secondary">
          {row.hours}
        </Text>
      ),
    },
    {
      key: 'staffCount',
      header: 'Staff Count',
      width: pixel(100),
      renderCell: (row) => (
        <Text size="sm" weight="medium">
          {row.staffCount} staff
        </Text>
      ),
    },
    {
      key: 'status',
      header: 'Status',
      width: pixel(120),
      renderCell: (row) => {
        const variant =
          row.status === 'active'
            ? 'success'
            : row.status === 'maintenance'
            ? 'warning'
            : 'error';
        return <Badge variant={variant} label={row.status} />;
      },
    },
    {
      key: 'actions',
      header: 'Actions',
      align: 'center',
      width: pixel(160),
      renderCell: (row) => (
        <HStack hAlign="center">
          <DropdownMenu
            button={{
              variant: 'secondary',
              size: 'sm',
              label: 'Manage',
              icon: <Icon icon="moreHorizontal" size="sm" />,
            }}
            menuWidth={180}
            items={[
              {
                label: row.status === 'active' ? 'Disable store' : 'Enable store',
                onClick: () => handleToggleStatus(row.id),
              },
              {type: 'divider'},
              {
                label: 'Remove store',
                onClick: () => handleRemove(row.id, row.name),
              },
            ]}
          />
        </HStack>
      ),
    },
  ];

  return (
    <VStack gap={5}>
      <StaticPanel
        title="Store Locations & Outlets"
        subtitle="Manage active branches, operating hours, assigned managers and status."
        actions={
          <Button
            variant="primary"
            size="sm"
            label={isAdding ? 'Cancel' : 'Add Store Location'}
            onClick={() => setIsAdding(!isAdding)}
          />
        }
      >
        <VStack gap={4}>
          {isAdding ? (
            <VStack gap={3} padding={4}>
              <Heading level={3}>Add New Branch Location</Heading>
              <HStack gap={3} vAlign="end" wrap="wrap">
                <TextInput
                  label="Store Name"
                  value={name}
                  onChange={setName}
                  placeholder="e.g. HSR Layout 27th Main"
                />
                <TextInput
                  label="Address / Landmark"
                  value={location}
                  onChange={setLocation}
                  placeholder="HSR Layout, Bengaluru"
                />
                <Selector
                  label="Store Manager"
                  value={manager}
                  onChange={(v) => setManager(v)}
                  options={[
                    'Vikram Seth',
                    'Priya Sharma',
                    'Deepa Nair',
                    'Unassigned',
                  ]}
                />
                <TextInput
                  label="Hours"
                  value={hours}
                  onChange={setHours}
                  placeholder="09:00 – 22:00"
                />
                <Button
                  variant="primary"
                  size="sm"
                  label="Create Store"
                  onClick={handleAddStore}
                />
              </HStack>
            </VStack>
          ) : null}

          <ResponsiveTable
            columns={columns}
            data={stores}
            primaryKey="name"
          />
        </VStack>
      </StaticPanel>
    </VStack>
  );
}
