import { Book, Code2, Copy, Eye } from 'lucide-react';

import { useState } from 'react';

import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Separator } from '@/Components/ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/Components/ui/tabs';

/**
 * DS-005: Component Documentation Page
 *
 * This component provides a centralized documentation showcase for UI components.
 * Useful for:
 * - Visual regression testing
 * - Design system documentation
 * - Component state exploration
 * - Developer onboarding
 *
 * Usage:
 * ```tsx
 * import ComponentShowcase from '@/Components/ComponentShowcase';
 *
 * export default function ShowcasePage() {
 *   return <ComponentShowcase />;
 * }
 * ```
 *
 * To add more components to this showcase:
 * 1. Create a new section in the `components` array below
 * 2. Include example code and preview props
 * 3. Document the component's purpose and usage
 */

interface ComponentExample {
  name: string;
  description: string;
  category: 'forms' | 'feedback' | 'navigation' | 'layout' | 'data-display';
  component: React.ReactNode;
  code: string;
  documentation?: string;
}

const ButtonShowcase: ComponentExample = {
  name: 'Button',
  description: 'Primary interactive element for user actions',
  category: 'forms',
  component: (
    <div className="flex flex-wrap gap-2">
      <Button>Default</Button>
      <Button variant="secondary">Secondary</Button>
      <Button variant="destructive">Destructive</Button>
      <Button variant="outline">Outline</Button>
      <Button variant="ghost">Ghost</Button>
      <Button size="sm">Small</Button>
      <Button size="lg">Large</Button>
      <Button disabled>Disabled</Button>
    </div>
  ),
  code: `<Button>Click me</Button>
<Button variant="secondary">Secondary</Button>
<Button variant="destructive">Delete</Button>
<Button disabled>Disabled</Button>`,
  documentation:
    'Use Button for primary actions. Variants: default, secondary, destructive, outline, ghost. Sizes: sm, md (default), lg.',
};

const InputShowcase: ComponentExample = {
  name: 'Input',
  description: 'Text input field for user data entry',
  category: 'forms',
  component: (
    <div className="flex flex-col gap-4">
      <div className="flex flex-col gap-2">
        <Label htmlFor="input-default">Default Input</Label>
        <Input id="input-default" placeholder="Enter text..." />
      </div>
      <div className="flex flex-col gap-2">
        <Label htmlFor="input-disabled">Disabled Input</Label>
        <Input id="input-disabled" placeholder="Disabled..." disabled />
      </div>
      <div className="flex flex-col gap-2">
        <Label htmlFor="input-error">Input with Error (styled via aria-invalid)</Label>
        <Input id="input-error" placeholder="Error state..." aria-invalid="true" />
      </div>
    </div>
  ),
  code: `<Input placeholder="Enter text..." />
<Input placeholder="Disabled..." disabled />
<Input placeholder="Error state..." aria-invalid="true" />`,
  documentation: 'Use Input for single-line text entry. Supports disabled and error states via aria-invalid.',
};

const AllComponents: ComponentExample[] = [ButtonShowcase, InputShowcase];

const categories: Record<string, string> = {
  forms: 'Form Components',
  feedback: 'Feedback',
  navigation: 'Navigation',
  layout: 'Layout',
  'data-display': 'Data Display',
};

interface ComponentDetailProps {
  example: ComponentExample;
}

function ComponentDetail({ example }: ComponentDetailProps): JSX.Element {
  const [copied, setCopied] = useState(false);

  const handleCopyCode = (): void => {
    navigator.clipboard.writeText(example.code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="space-y-6 rounded-lg border bg-card p-6">
      <div>
        <h3 className="text-lg font-semibold">{example.name}</h3>
        <p className="text-sm text-muted-foreground">{example.description}</p>
      </div>

      <Separator />

      <div>
        <h4 className="mb-4 text-sm font-medium">Preview</h4>
        <div className="rounded-lg border bg-muted/50 p-6">{example.component}</div>
      </div>

      <Separator />

      <Tabs defaultValue="code" className="w-full">
        <TabsList>
          <TabsTrigger value="code">
            <Code2 className="mr-2 h-4 w-4" />
            Code
          </TabsTrigger>
          {example.documentation && (
            <TabsTrigger value="docs">
              <Book className="mr-2 h-4 w-4" />
              Docs
            </TabsTrigger>
          )}
        </TabsList>

        <TabsContent value="code" className="relative">
          <pre className="overflow-x-auto rounded-lg bg-muted p-4 text-sm">
            <code>{example.code}</code>
          </pre>
          <Button
            size="sm"
            variant="ghost"
            className="absolute right-2 top-2"
            onClick={handleCopyCode}
          >
            <Copy className="h-4 w-4" />
            {copied ? 'Copied' : 'Copy'}
          </Button>
        </TabsContent>

        {example.documentation && (
          <TabsContent value="docs" className="prose prose-sm max-w-none dark:prose-invert">
            <p>{example.documentation}</p>
          </TabsContent>
        )}
      </Tabs>
    </div>
  );
}

interface ComponentShowcaseProps {
  /**
   * Filter components by category
   * @default undefined (show all)
   */
  category?: string;
}

/**
 * Component Showcase
 *
 * DS-005: Provides a visual documentation page for all UI components.
 * Useful for design system review, testing, and developer reference.
 */
export default function ComponentShowcase({ category }: ComponentShowcaseProps): JSX.Element {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>(category || '');

  const filteredComponents = AllComponents.filter((comp) => {
    const matchesSearch = comp.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      comp.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = !selectedCategory || comp.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  return (
    <div className="space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-4xl font-bold">Component Library</h1>
        <p className="mt-2 text-lg text-muted-foreground">
          Visual documentation and showcase of reusable UI components. Use these as reference for
          building consistent interfaces.
        </p>
      </div>

      {/* Search and Filter */}
      <div className="space-y-4">
        <div>
          <Label htmlFor="component-search">Search Components</Label>
          <Input
            id="component-search"
            placeholder="Button, Input, Select..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="mt-2"
          />
        </div>

        <div>
          <Label>Filter by Category</Label>
          <div className="mt-2 flex flex-wrap gap-2">
            <Button
              variant={selectedCategory === '' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setSelectedCategory('')}
            >
              All
            </Button>
            {Object.entries(categories).map(([key, label]) => (
              <Button
                key={key}
                variant={selectedCategory === key ? 'default' : 'outline'}
                size="sm"
                onClick={() => setSelectedCategory(key)}
              >
                {label}
              </Button>
            ))}
          </div>
        </div>
      </div>

      {/* Components Grid */}
      <div className="space-y-6">
        {filteredComponents.length === 0 ? (
          <div className="rounded-lg border border-dashed bg-muted/50 p-8 text-center">
            <Eye className="mx-auto mb-3 h-8 w-8 text-muted-foreground" />
            <p className="text-muted-foreground">
              No components found. Try adjusting your search or filters.
            </p>
          </div>
        ) : (
          filteredComponents.map((component) => (
            <ComponentDetail key={component.name} example={component} />
          ))
        )}
      </div>

      {/* Footer */}
      <div className="rounded-lg border bg-muted/50 p-6">
        <h3 className="font-semibold">Adding New Components</h3>
        <p className="mt-2 text-sm text-muted-foreground">
          To add a new component to this showcase, add a new object to the{' '}
          <code className="rounded bg-muted px-1 py-0.5">AllComponents</code> array in{' '}
          <code className="rounded bg-muted px-1 py-0.5">ComponentShowcase.tsx</code>.
        </p>
      </div>
    </div>
  );
}
