import { useState, useEffect } from 'react';
import { Routes, Route, useLocation, useNavigate, useSearchParams, Link } from 'react-router-dom';
import { AuthProvider, useAuth, ProtectedRoute } from '@persona-community-5/auth';
import { DashboardShell, Sidebar, Header, type NavItem } from '@persona-community-5/layout';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  Badge,
  Home,
  ImageIcon,
  Users,
  Settings,
  BarChart3,
  MessageSquare,
  Sparkles,
  Loader2,
  AlertCircle,
} from '@persona-community-5/ui';
import { LoginPage } from './pages/LoginPage';
import { RegisterPage } from './pages/RegisterPage';
import { ForgotPasswordPage } from './pages/ForgotPasswordPage';
import { ResetPasswordPage } from './pages/ResetPasswordPage';
import { VerifyEmailPage } from './pages/VerifyEmailPage';
import { SessionsPage } from './pages/SessionsPage';
import { ChatPage } from './pages/ChatPage';
import { GeneratePage } from './pages/GeneratePage';
import { MediaPage } from './pages/MediaPage';

const navItems: NavItem[] = [
  { label: 'Dashboard', href: '/', icon: Home },
  { label: 'Chat', href: '/chat', icon: MessageSquare },
  { label: 'Generate', href: '/generate', icon: Sparkles },
  { label: 'Media', href: '/media', icon: ImageIcon },
  { label: 'Analytics', href: '/analytics', icon: BarChart3 },
  { label: 'Users', href: '/users', icon: Users, badge: '12' },
  { label: 'Settings', href: '/settings', icon: Settings },
];

const pageTitles: Record<string, string> = {
  '/': 'Dashboard',
  '/chat': 'Chat',
  '/generate': 'Generate',
  '/media': 'Media',
  '/analytics': 'Analytics',
  '/users': 'Users',
  '/settings': 'Settings',
  '/settings/sessions': 'Sessions',
  '/settings/verify-email': 'Verify Email',
};

function DashboardPage() {
  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Welcome to creator-ui</CardTitle>
          <CardDescription>
            This is part of the{' '}
            <code className="bg-[var(--surface-200)] px-1.5 py-0.5 rounded text-sm">
              persona-community-5
            </code>{' '}
            monorepo, using the shared UI library and layout components.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex gap-3">
            <Button>Get Started</Button>
            <Button variant="outline">Documentation</Button>
          </div>
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Total Users</CardDescription>
            <CardTitle className="text-3xl">1,234</CardTitle>
          </CardHeader>
          <CardContent>
            <Badge variant="success">+12% from last month</Badge>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Active Sessions</CardDescription>
            <CardTitle className="text-3xl">567</CardTitle>
          </CardHeader>
          <CardContent>
            <Badge variant="info">Live</Badge>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardDescription>API Requests</CardDescription>
            <CardTitle className="text-3xl">89.2k</CardTitle>
          </CardHeader>
          <CardContent>
            <Badge variant="warning">High traffic</Badge>
          </CardContent>
        </Card>
      </div>

      <p className="text-sm text-[var(--text-muted)]">
        Edit this file at{' '}
        <code className="bg-[var(--surface-200)] px-1.5 py-0.5 rounded">
          apps/creator-ui/src/App.tsx
        </code>
      </p>
    </div>
  );
}

function UsersPage() {
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-[var(--text-primary)]">All Users</h2>
          <p className="text-sm text-[var(--text-muted)]">Manage your team members and their roles.</p>
        </div>
        <Button>Add User</Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {[
          { name: 'Alice Chen', role: 'Admin', status: 'Active' },
          { name: 'Bob Martinez', role: 'Editor', status: 'Active' },
          { name: 'Carol Singh', role: 'Viewer', status: 'Invited' },
        ].map((user) => (
          <Card key={user.name}>
            <CardHeader>
              <CardTitle className="text-base">{user.name}</CardTitle>
              <CardDescription>{user.role}</CardDescription>
            </CardHeader>
            <CardContent>
              <Badge variant={user.status === 'Active' ? 'success' : 'info'}>
                {user.status}
              </Badge>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}

function AnalyticsPage() {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Page Views</CardDescription>
            <CardTitle className="text-3xl">24.5k</CardTitle>
          </CardHeader>
          <CardContent>
            <Badge variant="success">+8% this week</Badge>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Bounce Rate</CardDescription>
            <CardTitle className="text-3xl">32%</CardTitle>
          </CardHeader>
          <CardContent>
            <Badge variant="success">-3% improvement</Badge>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardDescription>Avg. Session</CardDescription>
            <CardTitle className="text-3xl">4m 12s</CardTitle>
          </CardHeader>
          <CardContent>
            <Badge variant="info">Stable</Badge>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Traffic Sources</CardTitle>
          <CardDescription>Where your visitors are coming from this month.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {[
              { source: 'Direct', visits: '8,421', pct: 34 },
              { source: 'Search', visits: '6,312', pct: 26 },
              { source: 'Social', visits: '5,105', pct: 21 },
              { source: 'Referral', visits: '4,662', pct: 19 },
            ].map((row) => (
              <div key={row.source} className="flex items-center justify-between">
                <span className="text-sm font-medium text-[var(--text-primary)]">{row.source}</span>
                <div className="flex items-center gap-3">
                  <div className="w-32 h-2 rounded-full bg-[var(--surface-200)] overflow-hidden">
                    <div
                      className="h-full rounded-full bg-[var(--accent)]"
                      style={{ width: `${row.pct}%` }}
                    />
                  </div>
                  <span className="text-sm text-[var(--text-muted)] w-16 text-right">{row.visits}</span>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function SettingsPage() {
  const { logout } = useAuth();
  const navigate = useNavigate();

  const handleLogout = async () => {
    await logout();
    navigate('/login');
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>General</CardTitle>
          <CardDescription>Manage your application settings and preferences.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {[
              { label: 'Application Name', value: 'persona-community-5' },
              { label: 'Environment', value: 'Production' },
              { label: 'Region', value: 'US West' },
            ].map((setting) => (
              <div key={setting.label} className="flex items-center justify-between py-2 border-b border-[var(--border-muted)] last:border-0">
                <span className="text-sm font-medium text-[var(--text-primary)]">{setting.label}</span>
                <Badge variant="outline">{setting.value}</Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Account</CardTitle>
          <CardDescription>Manage your account settings.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-primary)]">Sign Out</p>
              <p className="text-sm text-[var(--text-muted)]">Sign out of your account on this device.</p>
            </div>
            <Button variant="outline" onClick={handleLogout}>Sign Out</Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Danger Zone</CardTitle>
          <CardDescription>Irreversible actions for your application.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-primary)]">Delete Application</p>
              <p className="text-sm text-[var(--text-muted)]">Permanently remove this application and all its data.</p>
            </div>
            <Button variant="destructive">Delete</Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function LoadingScreen() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-[var(--surface-100)]">
      <div className="flex flex-col items-center gap-4">
        <Loader2 className="h-8 w-8 animate-spin text-[var(--accent)]" />
        <p className="text-sm text-[var(--text-muted)]">Loading...</p>
      </div>
    </div>
  );
}

function MagicLinkCallbackPage() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { loginWithMagicLink } = useAuth();
  const [error, setError] = useState<string | null>(null);
  const [verifying, setVerifying] = useState(true);

  useEffect(() => {
    const token = searchParams.get('token');
    const email = searchParams.get('email');

    if (!token || !email) {
      setError('Invalid magic link. Missing token or email.');
      setVerifying(false);
      return;
    }

    loginWithMagicLink({ email, token })
      .then(() => {
        navigate('/', { replace: true });
      })
      .catch((err) => {
        setError(err instanceof Error ? err.message : 'Magic link verification failed.');
        setVerifying(false);
      });
  }, [searchParams, loginWithMagicLink, navigate]);

  return (
    <div className="min-h-screen flex items-center justify-center bg-[var(--surface-100)]">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <CardTitle>{verifying ? 'Verifying Magic Link' : 'Verification Failed'}</CardTitle>
          <CardDescription>
            {verifying
              ? 'Please wait while we verify your magic link...'
              : 'We could not verify your magic link.'}
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col items-center gap-4">
          {verifying ? (
            <Loader2 className="h-8 w-8 animate-spin text-[var(--accent)]" />
          ) : (
            <>
              <div className="flex items-center gap-2 text-[var(--text-error, #ef4444)]">
                <AlertCircle className="h-5 w-5" />
                <p className="text-sm">{error}</p>
              </div>
              <Link to="/login">
                <Button variant="outline">Back to Login</Button>
              </Link>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

function AppLayout() {
  const location = useLocation();
  const navigate = useNavigate();
  const { user } = useAuth();

  const itemsWithActive = navItems.map((item) => ({
    ...item,
    active: location.pathname === item.href,
  }));

  const pageTitle = pageTitles[location.pathname] || 'Dashboard';

  return (
    <DashboardShell
      sidebar={
        <Sidebar
          logo={
            <span className="font-semibold text-lg">persona-community-5</span>
          }
          items={itemsWithActive}
          onNavigate={(href) => navigate(href)}
          footer={
            <div className="text-sm text-[var(--text-muted)]">
              {user?.email || 'v0.0.1'}
            </div>
          }
        />
      }
      header={
        <Header
          title={pageTitle}
          showSearch
          searchPlaceholder="Search..."
        />
      }
    >
      <Routes>
        <Route path="/" element={<DashboardPage />} />
        <Route path="/chat" element={<ChatPage />} />
        <Route path="/generate" element={<GeneratePage />} />
        <Route path="/media" element={<MediaPage />} />
        <Route path="/users" element={<UsersPage />} />
        <Route path="/analytics" element={<AnalyticsPage />} />
        <Route path="/settings" element={<SettingsPage />} />
        <Route path="/settings/sessions" element={<SessionsPage />} />
        <Route path="/settings/verify-email" element={<VerifyEmailPage />} />
      </Routes>
    </DashboardShell>
  );
}

function AppRoutes() {
  const location = useLocation();
  const navigate = useNavigate();

  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route path="/register" element={<RegisterPage />} />
      <Route path="/forgot-password" element={<ForgotPasswordPage />} />
      <Route path="/reset-password" element={<ResetPasswordPage />} />
      <Route path="/auth/magic-link/callback" element={<MagicLinkCallbackPage />} />
      <Route
        path="/*"
        element={
          <ProtectedRoute
            redirectTo="/login"
            onRedirect={(path) => {
              // Navigate to login, storing current location for redirect after login
              navigate(path, { state: { from: location.pathname }, replace: true });
            }}
            fallback={<LoadingScreen />}
          >
            <AppLayout />
          </ProtectedRoute>
        }
      />
    </Routes>
  );
}

function App() {
  // Determine API base URL from environment or current origin
  const apiBaseUrl = import.meta.env.VITE_API_URL || '';

  return (
    <AuthProvider authBaseUrl={`${apiBaseUrl}/api/persona-api`}>
      <AppRoutes />
    </AuthProvider>
  );
}

export default App;
