import React, { useState, useEffect } from 'react';
import {
  Container,
  Title,
  Text,
  Card,
  SimpleGrid,
  Group,
  Badge,
  Button,
  Stack,
  Progress,
  ActionIcon,
  Paper,
  Divider,
  Alert,
} from '@mantine/core';
import {
  IconRocket,
  IconChartLine,
  IconUsers,
  IconRefresh,
  IconCheck,
  IconInfoCircle,
  IconPlus,
} from '@tabler/icons-react';
import { 
  DataTable, 
  TableColumn,
  FormSidebar, 
  FormField 
} from '@skybridge/web-components';

const DemoApp: React.FC = () => {
  const [progress, setProgress] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [showTable, setShowTable] = useState(false);
  const [sidebarOpened, setSidebarOpened] = useState(false);
  const [demoData, setDemoData] = useState([
    { id: '1', name: 'John Doe', email: 'john@example.com', status: 'active', role: 'admin', created_at: '2024-01-15' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', status: 'active', role: 'user', created_at: '2024-02-20' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', status: 'inactive', role: 'viewer', created_at: '2024-03-10' },
  ]);

  useEffect(() => {
    const timer = setInterval(() => {
      setProgress((prev) => (prev >= 100 ? 0 : prev + 1));
    }, 100);
    return () => clearInterval(timer);
  }, []);

  const handleRefresh = () => {
    setIsLoading(true);
    setTimeout(() => setIsLoading(false), 1500);
  };

  const stats = [
    { label: 'Active Users', value: '1,234', icon: IconUsers, color: 'blue' },
    { label: 'Total Revenue', value: '$45,678', icon: IconChartLine, color: 'green' },
    { label: 'Projects', value: '89', icon: IconRocket, color: 'orange' },
  ];

  const features = [
    { title: 'Real-time Analytics', description: 'Monitor your data in real-time' },
    { title: 'Team Collaboration', description: 'Work together seamlessly' },
    { title: 'Cloud Integration', description: 'Connect with cloud services' },
    { title: 'Custom Reports', description: 'Generate detailed reports' },
  ];

  const tableColumns: TableColumn[] = [
    { key: 'name', label: 'Name', sortable: true },
    { key: 'email', label: 'Email', sortable: true },
    { key: 'role', label: 'Role', render: (value) => <Badge variant="light" size="sm">{value}</Badge> },
    { key: 'status', label: 'Status' }, // Uses default status rendering
    { key: 'created_at', label: 'Created', render: (value) => new Date(value).toLocaleDateString() },
  ];

  const formFields: FormField[] = [
    { name: 'name', label: 'Full Name', type: 'text', required: true, placeholder: 'Enter full name' },
    { name: 'email', label: 'Email', type: 'email', required: true, placeholder: 'Enter email address', validation: { email: true } },
    { 
      name: 'role', 
      label: 'Role', 
      type: 'select', 
      required: true,
      options: [
        { value: 'admin', label: 'Admin' },
        { value: 'user', label: 'User' },
        { value: 'viewer', label: 'Viewer' },
      ],
      defaultValue: 'user'
    },
    { 
      name: 'status', 
      label: 'Status', 
      type: 'select', 
      required: true,
      options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' },
      ],
      defaultValue: 'active'
    },
  ];

  const handleFormSubmit = async (values: any) => {
    // Simulate API call
    console.log('Form submitted:', values);
    const newItem = {
      id: Date.now().toString(),
      ...values,
      created_at: new Date().toISOString().split('T')[0]
    };
    setDemoData([...demoData, newItem]);
  };

  const handleEdit = (item: any) => {
    console.log('Edit item:', item);
    // Would normally open form with item data
    setSidebarOpened(true);
  };

  const handleDelete = async (item: any) => {
    setDemoData(demoData.filter(d => d.id !== item.id));
  };

  return (
    <Container size="xl" py="xl">
      <Stack gap="xl">
        <Group justify="space-between" align="center">
          <div>
            <Title order={1}>Demo Application</Title>
            <Text c="dimmed" size="lg" mt="xs">
              A sample federated application showcasing module federation
            </Text>
          </div>
          <ActionIcon
            size="lg"
            variant="light"
            loading={isLoading}
            onClick={handleRefresh}
          >
            <IconRefresh size={18} />
          </ActionIcon>
        </Group>

        <Alert icon={<IconInfoCircle size={16} />} title="Welcome!" color="blue" variant="light">
          This is a demo application loaded via Module Federation. It demonstrates how 
          microfrontends can be seamlessly integrated into the shell application.
        </Alert>

        <SimpleGrid cols={{ base: 1, sm: 3 }} spacing="md">
          {stats.map((stat) => (
            <Paper key={stat.label} p="md" radius="md" withBorder>
              <Group justify="space-between">
                <div>
                  <Text c="dimmed" size="sm" fw={500} tt="uppercase">
                    {stat.label}
                  </Text>
                  <Text fw={700} size="xl">
                    {stat.value}
                  </Text>
                </div>
                <stat.icon size={24} color={`var(--mantine-color-${stat.color}-6)`} />
              </Group>
            </Paper>
          ))}
        </SimpleGrid>

        <Card shadow="sm" padding="lg" radius="md" withBorder>
          <Card.Section withBorder inheritPadding py="xs">
            <Group justify="space-between">
              <Text fw={500}>System Performance</Text>
              <Badge color="green" variant="light">
                Healthy
              </Badge>
            </Group>
          </Card.Section>

          <Card.Section inheritPadding py="md">
            <Stack gap="xs">
              <Text size="sm" c="dimmed">
                CPU Usage: {progress.toFixed(1)}%
              </Text>
              <Progress value={progress} size="sm" color="blue" animated />
            </Stack>
          </Card.Section>
        </Card>

        <div>
          <Title order={2} mb="md">Features</Title>
          <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
            {features.map((feature, index) => (
              <Card key={index} shadow="sm" padding="lg" radius="md" withBorder>
                <Group mb="xs">
                  <IconCheck size={16} color="var(--mantine-color-green-6)" />
                  <Text fw={500}>{feature.title}</Text>
                </Group>
                <Text size="sm" c="dimmed">
                  {feature.description}
                </Text>
              </Card>
            ))}
          </SimpleGrid>
        </div>

        <Divider />

        <div>
          <Title order={2} mb="md">Shared Components Demo</Title>
          <Text c="dimmed" mb="lg">
            Demonstration of shared components from @skybridge/web-components
          </Text>
          
          <Group mb="md">
            <Button 
              leftSection={<IconPlus size={16} />} 
              onClick={() => setShowTable(!showTable)}
            >
              {showTable ? 'Hide' : 'Show'} DataTable Demo
            </Button>
            <Button 
              variant="outline" 
              onClick={() => setSidebarOpened(true)}
            >
              Show FormSidebar Demo
            </Button>
          </Group>

          {showTable && (
            <DataTable
              data={demoData}
              columns={tableColumns}
              title="Demo User Management"
              searchable
              onAdd={() => setSidebarOpened(true)}
              onEdit={handleEdit}
              onDelete={handleDelete}
              emptyMessage="No demo data available"
            />
          )}
        </div>

        <Divider />

        <Group justify="center">
          <Button variant="outline" size="md">
            View Documentation
          </Button>
          <Button size="md">
            Get Started
          </Button>
        </Group>
      </Stack>
      
      <FormSidebar
        opened={sidebarOpened}
        onClose={() => setSidebarOpened(false)}
        onSuccess={() => {
          setSidebarOpened(false);
          setShowTable(true); // Show table after successful form submission
        }}
        title="Demo User"
        fields={formFields}
        onSubmit={handleFormSubmit}
        width={400}
      />
    </Container>
  );
};

export default DemoApp;