import type { Meta, StoryObj } from '@storybook/react'
import { Users, Package, FileText, Settings, Key } from 'lucide-react'
import { Resource } from '../components/resource'
import { ResourcesProvider, useResources, useResource } from '../context/resource-context'

// =============================================================================
// Mock View Components
// =============================================================================

const UsersList = () => (
  <div className="rounded-lg border p-4">
    <h3 className="font-semibold">Users List View</h3>
    <p className="text-muted-foreground text-sm">Displays all users in a table</p>
  </div>
)

const UserShow = ({ id }: { id: string | number }) => (
  <div className="rounded-lg border p-4">
    <h3 className="font-semibold">User Detail View</h3>
    <p className="text-muted-foreground text-sm">Showing user: {id}</p>
  </div>
)

const UserCreate = () => (
  <div className="rounded-lg border p-4">
    <h3 className="font-semibold">Create User Form</h3>
    <p className="text-muted-foreground text-sm">Form to create a new user</p>
  </div>
)

const UserEdit = ({ id }: { id: string | number }) => (
  <div className="rounded-lg border p-4">
    <h3 className="font-semibold">Edit User Form</h3>
    <p className="text-muted-foreground text-sm">Editing user: {id}</p>
  </div>
)

const ProductsList = () => (
  <div className="rounded-lg border p-4">
    <h3 className="font-semibold">Products List View</h3>
    <p className="text-muted-foreground text-sm">Displays all products in a grid</p>
  </div>
)

// =============================================================================
// Helper Components for Stories
// =============================================================================

/**
 * Display registered resources for debugging
 */
const ResourcesDebugger = () => {
  const { resources } = useResources()
  return (
    <div className="mt-4 rounded-lg border bg-muted/50 p-4">
      <h4 className="mb-2 font-semibold">Registered Resources ({resources.length})</h4>
      {resources.length === 0 ? (
        <p className="text-muted-foreground text-sm">No resources registered yet</p>
      ) : (
        <ul className="space-y-1 text-sm">
          {resources.map((r) => (
            <li key={r.name} className="flex items-center gap-2">
              {r.icon && <r.icon className="size-4" />}
              <span className="font-medium">{r.labelPlural ?? r.label ?? r.name}</span>
              <span className="text-muted-foreground">({r.name})</span>
              <span className="text-xs text-muted-foreground">
                [{r.list ? 'list' : ''}{r.show ? ' show' : ''}{r.create ? ' create' : ''}{r.edit ? ' edit' : ''}]
              </span>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}

/**
 * Display current resource context
 */
const ResourceContextDisplay = () => {
  const context = useResource()
  return (
    <div className="mt-4 rounded-lg border bg-muted/50 p-4">
      <h4 className="mb-2 font-semibold">Resource Context</h4>
      <dl className="grid grid-cols-2 gap-2 text-sm">
        <dt className="text-muted-foreground">Resource:</dt>
        <dd className="font-medium">{context.resource}</dd>
        <dt className="text-muted-foreground">Has List:</dt>
        <dd>{context.hasList ? 'Yes' : 'No'}</dd>
        <dt className="text-muted-foreground">Has Create:</dt>
        <dd>{context.hasCreate ? 'Yes' : 'No'}</dd>
        <dt className="text-muted-foreground">Has Edit:</dt>
        <dd>{context.hasEdit ? 'Yes' : 'No'}</dd>
        <dt className="text-muted-foreground">Has Show:</dt>
        <dd>{context.hasShow ? 'Yes' : 'No'}</dd>
        {context.id && (
          <>
            <dt className="text-muted-foreground">Current ID:</dt>
            <dd>{context.id}</dd>
          </>
        )}
      </dl>
    </div>
  )
}

// =============================================================================
// Story Meta
// =============================================================================

const meta: Meta<typeof Resource> = {
  title: 'App/Resource',
  component: Resource,
  tags: ['autodocs'],
  parameters: {
    layout: 'padded',
  },
  decorators: [
    (Story) => (
      <ResourcesProvider>
        <div className="space-y-4">
          <Story />
          <ResourcesDebugger />
        </div>
      </ResourcesProvider>
    ),
  ],
}

export default meta
type Story = StoryObj<typeof Resource>

// =============================================================================
// Stories
// =============================================================================

/**
 * Basic resource registration with all CRUD operations.
 */
export const Default: Story = {
  args: {
    name: 'users',
    label: 'User',
    labelPlural: 'Users',
    icon: Users,
    list: UsersList,
    show: UserShow,
    create: UserCreate,
    edit: UserEdit,
  },
  render: (args) => (
    <div>
      <h2 className="text-xl font-semibold">Resource Registration</h2>
      <p className="text-muted-foreground mt-1">
        The Resource component registers itself with ResourcesProvider on mount.
      </p>
      <Resource {...args} />
    </div>
  ),
}

/**
 * Resource with only list view - common for read-only resources.
 */
export const ListOnly: Story = {
  args: {
    name: 'products',
    label: 'Product',
    labelPlural: 'Products',
    icon: Package,
    list: ProductsList,
  },
  render: (args) => (
    <div>
      <h2 className="text-xl font-semibold">List-Only Resource</h2>
      <p className="text-muted-foreground mt-1">
        Some resources only need a list view (e.g., logs, analytics).
      </p>
      <Resource {...args} />
    </div>
  ),
}

/**
 * Multiple resources registered together.
 */
export const MultipleResources: Story = {
  render: () => (
    <div>
      <h2 className="text-xl font-semibold">Multiple Resources</h2>
      <p className="text-muted-foreground mt-1">
        Multiple Resource components can be registered in the same provider.
      </p>
      <Resource
        name="users"
        label="User"
        labelPlural="Users"
        icon={Users}
        list={UsersList}
        edit={UserEdit}
      />
      <Resource
        name="products"
        label="Product"
        labelPlural="Products"
        icon={Package}
        list={ProductsList}
      />
      <Resource
        name="documents"
        label="Document"
        labelPlural="Documents"
        icon={FileText}
        list={() => <div>Documents List</div>}
        create={() => <div>Create Document</div>}
      />
    </div>
  ),
}

/**
 * Resource with children - wraps content in ResourceProvider context.
 */
export const WithChildren: Story = {
  render: () => (
    <div>
      <h2 className="text-xl font-semibold">Resource with Children</h2>
      <p className="text-muted-foreground mt-1">
        When children are provided, they receive resource context.
      </p>
      <Resource
        name="api-keys"
        label="API Key"
        labelPlural="API Keys"
        icon={Key}
        list={() => <div>API Keys List</div>}
        create={() => <div>Create API Key</div>}
      >
        <div className="mt-4 rounded-lg border p-4">
          <h3 className="font-semibold">Child Content</h3>
          <ResourceContextDisplay />
        </div>
      </Resource>
    </div>
  ),
}

/**
 * Resource with custom options.
 */
export const WithOptions: Story = {
  args: {
    name: 'settings',
    label: 'Setting',
    labelPlural: 'Settings',
    icon: Settings,
    list: () => <div>Settings List</div>,
    options: {
      allowBulkDelete: false,
      defaultSort: { field: 'name', order: 'ASC' },
      permissions: ['admin', 'editor'],
    },
  },
  render: (args) => (
    <div>
      <h2 className="text-xl font-semibold">Resource with Custom Options</h2>
      <p className="text-muted-foreground mt-1">
        Resources can include custom options for app-specific configuration.
      </p>
      <Resource {...args} />
      <div className="mt-4 rounded-lg border bg-muted/50 p-4">
        <h4 className="mb-2 font-semibold">Custom Options</h4>
        <pre className="text-xs">{JSON.stringify(args.options, null, 2)}</pre>
      </div>
    </div>
  ),
}
