import type { Meta, StoryObj } from "@storybook/react"
import { useState } from "react"
import { TextEditor, type TextEditorProps } from "./TextEditor"

/**
 * TextEditor is a powerful WYSIWYG editor built with TipTap that provides
 * rich text editing capabilities with formatting tools, resize functionality,
 * and extensive customization options.
 */
const meta = {
  title: "text-editor/TextEditor",
  component: TextEditor,
  parameters: {
    layout: "centered",
  },
  tags: ["autodocs"],
  args: {
    className: "w-full",
  },
} satisfies Meta<TextEditorProps>

export default meta
type Story = StoryObj<typeof meta>

const DefaultWrapper = (args: TextEditorProps) => {
  const [value, setValue] = useState("")
  return (
    <TextEditor
      {...args}
      value={value}
      onChange={setValue}
      placeholder="Start typing your content..."
    />
  )
}

/**
 * Default implementation of the TextEditor with basic configuration.
 */
export const Default: Story = {
  render: DefaultWrapper,
}

const WithContentWrapper = (args: TextEditorProps) => {
  const [value, setValue] = useState(`
    <h1>Welcome to Text Editor</h1>
    <p>This is a <strong>bold text</strong> and this is <em>italic text</em>.</p>
    <p>You can also add <u>underlined text</u> and <s>strikethrough text</s>.</p>
    <ul>
      <li>Bullet point one</li>
      <li>Bullet point two</li>
      <li>Bullet point three</li>
    </ul>
    <p>And even <a href="https://example.com">links</a> to external content.</p>
  `)
  return (
    <TextEditor
      {...args}
      value={value}
      onChange={setValue}
      placeholder="Start typing your content..."
    />
  )
}

/**
 * TextEditor with pre-filled content to showcase formatting capabilities.
 */
export const WithContent: Story = {
  render: WithContentWrapper,
}

const DisabledWrapper = (args: TextEditorProps) => {
  const [value] = useState(`
    <h2>Read-only Content</h2>
    <p>This editor is disabled and shows content in read-only mode.</p>
    <p>All toolbar actions are disabled and content cannot be edited.</p>
  `)
  return (
    <TextEditor {...args} value={value} disabled={true} placeholder="This editor is disabled" />
  )
}

/**
 * TextEditor in disabled state to show read-only functionality.
 */
export const Disabled: Story = {
  render: DisabledWrapper,
}

const WithErrorWrapper = (args: TextEditorProps) => {
  const [value, setValue] = useState("")
  return (
    <div className="space-y-2">
      <TextEditor
        {...args}
        value={value}
        onChange={setValue}
        error={true}
        placeholder="This field has an error state"
      />
      <p className="text-sm text-red-500">Please enter valid content</p>
    </div>
  )
}

/**
 * TextEditor with error state styling.
 */
export const WithError: Story = {
  render: WithErrorWrapper,
}

const CustomHeightWrapper = (args: TextEditorProps) => {
  const [value, setValue] = useState(`
    <p>This editor has a custom height of 600px.</p>
    <p>You can resize it using the handle in the bottom-right corner.</p>
    <p>Try adding more content to see how it behaves with scrolling:</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
    <p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  `)
  return (
    <TextEditor
      {...args}
      value={value}
      onChange={setValue}
      maxHeight={600}
      placeholder="Custom height editor"
    />
  )
}

/**
 * TextEditor with custom height constraints.
 */
export const CustomHeight: Story = {
  render: CustomHeightWrapper,
}

const CompactWrapper = (args: TextEditorProps) => {
  const [value, setValue] = useState("")
  return (
    <TextEditor
      {...args}
      value={value}
      onChange={setValue}
      maxHeight={250}
      placeholder="Compact editor for quick notes..."
      className="w-full max-w-2xl"
    />
  )
}

/**
 * Compact TextEditor with smaller height for inline usage.
 */
export const Compact: Story = {
  render: CompactWrapper,
}

const ControlledWrapper = (args: TextEditorProps) => {
  const [value, setValue] = useState("")
  const [wordCount, setWordCount] = useState(0)

  const handleChange = (newValue: string) => {
    setValue(newValue)
    // Calculate word count from plain text
    const text = newValue.replace(/<[^>]*>/g, "").trim()
    const count = text ? text.split(/\s+/).length : 0
    setWordCount(count)
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">Controlled Editor</h3>
        <div className="flex gap-4">
          <span className="text-sm text-gray-600">Words: {wordCount}</span>
          <button
            type="button"
            className="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600"
            onClick={() => setValue("")}
          >
            Clear
          </button>
        </div>
      </div>

      <TextEditor
        {...args}
        value={value}
        onChange={handleChange}
        placeholder="Type to see external word count..."
      />

      <div className="mt-4 p-4 bg-gray-100 rounded">
        <h4 className="font-medium mb-2">Raw HTML Output:</h4>
        <pre className="text-sm text-gray-700 whitespace-pre-wrap break-all">
          {value || "(empty)"}
        </pre>
      </div>
    </div>
  )
}

/**
 * Controlled TextEditor demonstrating external state management.
 */
export const Controlled: Story = {
  render: ControlledWrapper,
}
