import { useLanguage } from "@/hooks/use-language";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

interface Endpoint {
  method: string;
  path: string;
  description: string;
  descriptionAr: string;
  auth: boolean;
  adminOnly: boolean;
  requestBody?: Record<string, any>;
  responseBody?: Record<string, any>;
  exampleRequest?: string;
  exampleResponse?: string;
}

interface EndpointGroup {
  name: string;
  nameAr: string;
  endpoints: Endpoint[];
}

export default function ApiDocsPage() {
  const { t, language } = useLanguage();

  const endpointGroups: EndpointGroup[] = [
    {
      name: "Authentication",
      nameAr: "المصادقة",
      endpoints: [
        {
          method: "POST",
          path: "/api/login",
          description: "Log in with username and password",
          descriptionAr: "تسجيل الدخول باستخدام اسم المستخدم وكلمة المرور",
          auth: false,
          adminOnly: false,
          requestBody: {
            username: "string",
            password: "string"
          },
          responseBody: {
            id: "number",
            username: "string",
            name: "string",
            organization: "string",
            position: "string",
            phoneNumber: "string",
            email: "string",
            role: "string (user|admin|moderator)",
            isActive: "boolean",
            profileImage: "string (optional)",
            sessionId: "number | null",
            createdAt: "string (ISO date)",
            lastLogin: "string (ISO date) | null"
          },
          exampleRequest: `fetch('/api/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    username: 'your_username',
    password: 'your_password'
  })
})`,
          exampleResponse: `{
  "id": 1,
  "username": "admin",
  "name": "Admin User",
  "role": "admin",
  "isActive": true
}`
        },
        {
          method: "POST",
          path: "/api/logout",
          description: "Log out the current user",
          descriptionAr: "تسجيل خروج المستخدم الحالي",
          auth: true,
          adminOnly: false,
          exampleRequest: `fetch('/api/logout', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  }
})`
        },
        {
          method: "POST",
          path: "/api/users/:id/send-invitation",
          description: "Send an activation email to a user using SendGrid",
          descriptionAr: "إرسال بريد إلكتروني للتفعيل إلى المستخدم باستخدام SendGrid",
          auth: true,
          adminOnly: true,
          requestBody: {
            subject: "string",
            body: "string"
          },
          responseBody: {
            success: "boolean",
            message: "string"
          }
        },
        {
          method: "POST",
          path: "/api/users/:id/reset-password",
          description: "Reset a user's password",
          descriptionAr: "إعادة تعيين كلمة مرور المستخدم",
          auth: true,
          adminOnly: true,
          requestBody: {
            password: "string"
          }
        }
      ]
    },
    {
      name: "File Upload",
      nameAr: "رفع الملفات",
      endpoints: [
        {
          method: "POST",
          path: "/api/upload",
          description: "Upload an image file",
          descriptionAr: "رفع ملف صورة",
          auth: true,
          adminOnly: false,
          requestBody: {
            file: "multipart/form-data (image file)"
          },
          responseBody: {
            url: "string (relative path to uploaded file)"
          }
        }
      ]
    },
    {
      name: "Events",
      nameAr: "الفعاليات",
      endpoints: [
        {
          method: "GET",
          path: "/api/events",
          description: "Get list of all events",
          descriptionAr: "الحصول على قائمة جميع الفعاليات",
          auth: false,
          adminOnly: false,
          responseBody: {
            id: "number",
            eventName: "string",
            eventNameAr: "string",
            eventDescription: "string",
            eventDescriptionAr: "string",
            startDate: "string (ISO date)",
            endDate: "string (ISO date)",
            location: "string",
            locationAr: "string",
            eventLogo: "string (uploaded image URL)"
          }
        },
        {
          method: "POST",
          path: "/api/events",
          description: "Create a new event",
          descriptionAr: "إنشاء فعالية جديدة",
          auth: true,
          adminOnly: true,
          requestBody: {
            eventName: "string",
            eventNameAr: "string",
            eventDescription: "string",
            eventDescriptionAr: "string",
            startDate: "string (ISO date)",
            endDate: "string (ISO date)",
            location: "string",
            locationAr: "string",
            eventLogo: "string (uploaded image URL)"
          }
        },
        {
          method: "DELETE",
          path: "/api/events/:id",
          description: "Delete an event",
          descriptionAr: "حذف فعالية",
          auth: true,
          adminOnly: true
        }
      ]
    },
    {
      name: "Sessions",
      nameAr: "الجلسات",
      endpoints: [
        {
          method: "GET",
          path: "/api/sessions",
          description: "Get all sessions with speakers",
          descriptionAr: "الحصول على جميع الجلسات مع المتحدثين",
          auth: false,
          adminOnly: false,
          responseBody: {
            id: "number",
            title: "string",
            titleAr: "string",
            description: "string",
            descriptionAr: "string",
            startTime: "string (ISO date)",
            endTime: "string (ISO date)",
            eventId: "number",
            speakers: "array of Speaker objects"
          }
        },
        {
          method: "POST",
          path: "/api/sessions",
          description: "Create a new session",
          descriptionAr: "إنشاء جلسة جديدة",
          auth: true,
          adminOnly: true,
          requestBody: {
            title: "string",
            titleAr: "string",
            description: "string",
            descriptionAr: "string",
            startTime: "string (ISO date)",
            endTime: "string (ISO date)",
            eventId: "number"
          }
        },
        {
          method: "DELETE",
          path: "/api/sessions/:id",
          description: "Delete a session",
          descriptionAr: "حذف جلسة",
          auth: true,
          adminOnly: true
        }
      ]
    },
    {
      name: "Notifications",
      nameAr: "الإشعارات",
      endpoints: [
        {
          method: "POST",
          path: "/api/notifications/send",
          description: "Send a notification to all users",
          descriptionAr: "إرسال إشعار لجميع المستخدمين",
          auth: true,
          adminOnly: true,
          requestBody: {
            title: "string",
            body: "string",
            url: "string (optional)"
          },
          responseBody: {
            success: "boolean",
            message: "string"
          },
          exampleRequest: `// Using fetch
fetch('/api/notifications/send', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <your_token>'
  },
  body: JSON.stringify({
    title: 'New Event Added',
    body: 'Check out our latest event!',
    url: '/events/123'
  })
})

// Using axios
axios.post('/api/notifications/send', {
  title: 'New Event Added',
  body: 'Check out our latest event!',
  url: '/events/123'
}, {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <your_token>'
  }
})`,
          exampleResponse: `{
  "success": true,
  "message": "Notification sent successfully"
}`
        }
      ]
    },
    {
      name: "Polls",
      nameAr: "الاستطلاعات",
      endpoints: [
        {
          method: "GET",
          path: "/api/polls",
          description: "Get all polls",
          descriptionAr: "الحصول على جميع الاستطلاعات",
          auth: false,
          adminOnly: false,
          responseBody: {
            id: "number",
            title: "string",
            titleAr: "string",
            description: "string",
            descriptionAr: "string",
            startDate: "string (ISO date)",
            endDate: "string (ISO date)",
            isActive: "boolean",
            resultsPublished: "boolean"
          }
        },
        {
          method: "POST",
          path: "/api/polls",
          description: "Create a new poll",
          descriptionAr: "إنشاء استطلاع جديد",
          auth: true,
          adminOnly: true,
          requestBody: {
            title: "string",
            titleAr: "string",
            description: "string",
            descriptionAr: "string",
            startDate: "string (ISO date)",
            endDate: "string (ISO date)",
            questions: "array of PollQuestion objects"
          }
        },
        {
          method: "DELETE",
          path: "/api/polls/:id",
          description: "Delete a poll",
          descriptionAr: "حذف استطلاع",
          auth: true,
          adminOnly: true
        }
      ]
    },
    {
      name: "Questions",
      nameAr: "الأسئلة",
      endpoints: [
        {
          method: "POST",
          path: "/api/questions",
          description: "Submit a question for a session",
          descriptionAr: "تقديم سؤال لجلسة",
          auth: true,
          adminOnly: false,
          requestBody: {
            question: "string",
            sessionId: "number"
          }
        },
        {
          method: "POST",
          path: "/api/questions/:id/respond",
          description: "Respond to a question",
          descriptionAr: "الرد على سؤال",
          auth: true,
          adminOnly: true,
          requestBody: {
            response: "string"
          }
        },
        {
          method: "DELETE",
          path: "/api/questions/:id",
          description: "Delete a question",
          descriptionAr: "حذف سؤال",
          auth: true,
          adminOnly: true
        }
      ]
    },
    {
      name: "Streaming",
      nameAr: "البث المباشر",
      endpoints: [
        {
          method: "POST",
          path: "/api/rtmp/start",
          description: "Start the RTMP server for streaming",
          descriptionAr: "تشغيل خادم RTMP للبث",
          auth: true,
          adminOnly: true,
          responseBody: {
            success: "boolean",
            message: "string"
          }
        },
        {
          method: "POST",
          path: "/api/rtmp/stop",
          description: "Stop the RTMP server",
          descriptionAr: "إيقاف خادم RTMP",
          auth: true,
          adminOnly: true,
          responseBody: {
            success: "boolean",
            message: "string"
          }
        },
        {
          method: "GET",
          path: "/api/rtmp/status",
          description: "Get the current RTMP server status",
          descriptionAr: "الحصول على حالة خادم RTMP الحالية",
          auth: true,
          adminOnly: false,
          responseBody: {
            isRunning: "boolean",
            activeStreams: "number",
            uptime: "string"
          }
        }
      ]
    },
    {
      name: "AI Services",
      nameAr: "خدمات الذكاء الاصطناعي",
      endpoints: [
        {
          method: "POST",
          path: "/api/ai/chat",
          description: "Send a message to the AI chatbot",
          descriptionAr: "إرسال رسالة إلى روبوت المحادثة الذكي",
          auth: true,
          adminOnly: false,
          requestBody: {
            query: "string",
            context: "string (optional)"
          },
          responseBody: {
            answer: "string",
            confidence: "number (0-1)"
          }
        },
        {
          method: "POST",
          path: "/api/transcribe/session/:sessionId",
          description: "Start real-time transcription for a session",
          descriptionAr: "بدء النسخ المباشر للجلسة",
          auth: true,
          adminOnly: true,
          requestBody: {
            sessionId: "number",
            language: "string (optional, defaults to 'en')"
          }
        }
      ]
    },
    {
      name: "Media",
      nameAr: "الوسائط",
      endpoints: [
        {
          method: "GET",
          path: "/api/media",
          description: "Get all media items",
          descriptionAr: "الحصول على جميع عناصر الوسائط",
          auth: false,
          adminOnly: false,
          responseBody: {
            id: "number",
            type: "string ('image' | 'video')",
            title: "string",
            titleAr: "string",
            description: "string",
            descriptionAr: "string",
            url: "string (image URL or video embed code)",
            thumbnail: "string (optional, for videos)",
            uploaderId: "number"
          }
        },
        {
          method: "POST",
          path: "/api/media",
          description: "Create a new media item",
          descriptionAr: "إنشاء عنصر وسائط جديد",
          auth: true,
          adminOnly: true,
          requestBody: {
            type: "string ('image' | 'video')",
            title: "string",
            titleAr: "string",
            description: "string",
            descriptionAr: "string",
            url: "string (uploaded image URL or video embed code)",
            thumbnail: "string (optional, for videos)"
          }
        },
        {
          method: "DELETE",
          path: "/api/media/:id",
          description: "Delete a media item",
          descriptionAr: "حذف عنصر وسائط",
          auth: true,
          adminOnly: true
        }
      ]
    },
    {
      name: "News",
      nameAr: "الأخبار",
      endpoints: [
        {
          method: "GET",
          path: "/api/news",
          description: "Get all news articles",
          descriptionAr: "الحصول على جميع المقالات الإخبارية",
          auth: false,
          adminOnly: false,
          responseBody: {
            id: "number",
            title: "string",
            titleAr: "string",
            content: "string",
            contentAr: "string",
            image: "string (uploaded image URL)",
            publishDate: "string (ISO date)",
            authorId: "number"
          }
        },
        {
          method: "POST",
          path: "/api/news",
          description: "Create a news article",
          descriptionAr: "إنشاء مقال إخباري",
          auth: true,
          adminOnly: true,
          requestBody: {
            title: "string",
            titleAr: "string",
            content: "string",
            contentAr: "string",
            image: "string (uploaded image URL)",
            isPublished: "boolean"
          }
        },
        {
          method: "DELETE",
          path: "/api/news/:id",
          description: "Delete a news article",
          descriptionAr: "حذف مقال إخباري",
          auth: true,
          adminOnly: true
        }
      ]
    },
    {
      name: "Speakers",
      nameAr: "المتحدثون",
      endpoints: [
        {
          method: "GET",
          path: "/api/speakers",
          description: "Get all speakers",
          descriptionAr: "الحصول على جميع المتحدثين",
          auth: false,
          adminOnly: false,
          responseBody: {
            id: "number",
            name: "string",
            nameAr: "string",
            bio: "string",
            bioAr: "string",
            title: "string",
            titleAr: "string",
            organization: "string",
            organizationAr: "string",
            position: "string",
            positionAr: "string",
            imageUrl: "string (uploaded image URL)"
          }
        },
        {
          method: "POST",
          path: "/api/speakers",
          description: "Create a new speaker",
          descriptionAr: "إضافة متحدث جديد",
          auth: true,
          adminOnly: true,
          requestBody: {
            name: "string",
            nameAr: "string",
            bio: "string",
            bioAr: "string",
            title: "string",
            titleAr: "string",
            organization: "string",
            organizationAr: "string",
            position: "string",
            positionAr: "string",
            imageUrl: "string (uploaded image URL)"
          }
        },
        {
          method: "DELETE",
          path: "/api/speakers/:id",
          description: "Delete a speaker",
          descriptionAr: "حذف متحدث",
          auth: true,
          adminOnly: true
        }
      ]
    },
    {
      name: "Users",
      nameAr: "المستخدمون",
      endpoints: [
        {
          method: "GET",
          path: "/api/users",
          description: "Get all users",
          descriptionAr: "الحصول على جميع المستخدمين",
          auth: true,
          adminOnly: true,
          responseBody: {
            id: "number",
            username: "string",
            name: "string",
            email: "string",
            role: "string",
            organization: "string",
            position: "string",
            isActive: "boolean",
            sessionId: "number | null"
          }
        },
        {
          method: "POST",
          path: "/api/register",
          description: "Create a new user",
          descriptionAr: "إنشاء مستخدم جديد",
          auth: true,
          adminOnly: true,
          requestBody: {
            username: "string",
            password: "string",
            name: "string",
            email: "string",
            role: "string",
            organization: "string",
            position: "string",
            sessionId: "number | null"
          }
        },
        {
          method: "PATCH",
          path: "/api/users/:id",
          description: "Update a user",
          descriptionAr: "تحديث معلومات المستخدم",
          auth: true,
          adminOnly: true,
          requestBody: {
            name: "string (optional)",
            email: "string (optional)",
            role: "string (optional)",
            organization: "string (optional)",
            position: "string (optional)",
            sessionId: "number | null (optional)"
          }
        },
        {
          method: "DELETE",
          path: "/api/users/:id",
          description: "Delete a user",
          descriptionAr: "حذف مستخدم",
          auth: true,
          adminOnly: true
        }
      ]
    },
    {
      name: "Email Integration",
      nameAr: "تكامل البريد الإلكتروني",
      endpoints: [
        {
          method: "POST",
          path: "/api/email/send",
          description: "Send a custom email using SendGrid",
          descriptionAr: "إرسال بريد إلكتروني مخصص باستخدام SendGrid",
          auth: true,
          adminOnly: true,
          requestBody: {
            to: "string (email)",
            subject: "string",
            body: "string",
            template: "string (optional)",
            variables: "Record<string, string> (optional)"
          }
        }
      ]
    }
  ];

  return (
    <div className="container mx-auto py-8 space-y-8">
      <div className="flex items-center justify-between mb-8">
        <h1 className="text-4xl font-bold">
          {t("API Documentation", "توثيق واجهة برمجة التطبيقات")}
        </h1>
      </div>

      <Tabs defaultValue="overview" className="w-full">
        <TabsList className="mb-8 w-full justify-start border-b">
          <TabsTrigger value="overview" className="text-lg">{t("Overview", "نظرة عامة")}</TabsTrigger>
          <TabsTrigger value="auth" className="text-lg">{t("Authentication", "المصادقة")}</TabsTrigger>
          <TabsTrigger value="endpoints" className="text-lg">{t("Endpoints", "نقاط النهاية")}</TabsTrigger>
          <TabsTrigger value="examples" className="text-lg">{t("Examples", "أمثلة")}</TabsTrigger>
          <TabsTrigger value="database" className="text-lg">{t("Database", "قاعدة البيانات")}</TabsTrigger>
          <TabsTrigger value="services" className="text-lg">{t("External Services", "الخدمات الخارجية")}</TabsTrigger>
        </TabsList>

        <TabsContent value="overview">
          <Card>
            <CardHeader>
              <CardTitle>{t("API Overview", "نظرة عامة على API")}</CardTitle>
              <CardDescription>
                {t(
                  "This documentation provides information about the available API endpoints for the Event Management platform.",
                  "يوفر هذا التوثيق معلومات حول نقاط النهاية المتاحة لمنصة إدارة الفعاليات."
                )}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div>
                <h3 className="text-xl font-semibold mb-4">
                  {t("Base URL", "عنوان URL الأساسي")}
                </h3>
                <code className="block bg-muted p-4 rounded-lg text-base font-mono">
                  {window.location.origin}
                </code>
              </div>

              <div>
                <h3 className="text-xl font-semibold mb-4">
                  {t("Authentication", "المصادقة")}
                </h3>
                <p className="text-muted-foreground">
                  {t(
                    "Most endpoints require authentication using session cookies. Log in first using the /api/login endpoint to obtain a session.",
                    "تتطلب معظم نقاط النهاية المصادقة باستخدام ملفات تعريف الارتباط للجلسة. قم بتسجيل الدخول أولاً باستخدام نقطة النهاية /api/login للحصول على جلسة."
                  )}
                </p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="endpoints">
          <div className="grid gap-8">
            {endpointGroups.map((group) => (
              <Card key={group.name}>
                <CardHeader>
                  <CardTitle>
                    {language === "en" ? group.name : group.nameAr}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-8">
                    {group.endpoints.map((endpoint, index) => (
                      <div key={`${endpoint.method}-${endpoint.path}-${index}`} 
                           className="border rounded-lg p-6 bg-card hover:bg-accent/5 transition-colors">
                        <div className="flex items-center gap-4 mb-4">
                          <span className={`px-3 py-1.5 rounded-md text-sm font-mono font-medium ${
                            endpoint.method === "GET" ? "bg-blue-100 text-blue-700" :
                            endpoint.method === "POST" ? "bg-green-100 text-green-700" :
                            endpoint.method === "PUT" ? "bg-yellow-100 text-yellow-700" :
                            endpoint.method === "DELETE" ? "bg-red-100 text-red-700" :
                            endpoint.method === "PATCH" ? "bg-purple-100 text-purple-700" :
                            "bg-gray-100 text-gray-700"
                          }`}>
                            {endpoint.method}
                          </span>
                          <code className="text-base font-mono bg-muted px-3 py-1.5 rounded">
                            {endpoint.path}
                          </code>
                        </div>

                        <p className="text-base text-muted-foreground mb-4">
                          {language === "en" ? endpoint.description : endpoint.descriptionAr}
                        </p>

                        <div className="flex gap-2 mb-4">
                          {endpoint.auth && (
                            <span className="text-xs bg-orange-100 text-orange-700 px-2 py-1 rounded-full font-medium">
                              {t("Requires Auth", "يتطلب المصادقة")}
                            </span>
                          )}
                          {endpoint.adminOnly && (
                            <span className="text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded-full font-medium">
                              {t("Admin Only", "للمشرف فقط")}
                            </span>
                          )}
                        </div>

                        {(endpoint.requestBody || endpoint.responseBody || endpoint.exampleRequest) && (
                          <div className="grid gap-4 mt-6">
                            {endpoint.requestBody && (
                              <div>
                                <h4 className="text-sm font-medium mb-2">
                                  {t("Request Body", "هيكل الطلب")}:
                                </h4>
                                <pre className="bg-muted p-4 rounded-lg text-sm font-mono overflow-x-auto">
                                  {JSON.stringify(endpoint.requestBody, null, 2)}
                                </pre>
                              </div>
                            )}
                            {endpoint.responseBody && (
                              <div>
                                <h4 className="text-sm font-medium mb-2">
                                  {t("Response", "الاستجابة")}:
                                </h4>
                                <pre className="bg-muted p-4 rounded-lg text-sm font-mono overflow-x-auto">
                                  {JSON.stringify(endpoint.responseBody, null, 2)}
                                </pre>
                              </div>
                            )}
                            {endpoint.exampleRequest && (
                              <div>
                                <h4 className="text-sm font-medium mb-2">
                                  {t("Example Request", "مثال على الطلب")}:
                                </h4>
                                <pre className="bg-muted p-4 rounded-lg text-sm font-mono overflow-x-auto">
                                  {endpoint.exampleRequest}
                                </pre>
                              </div>
                            )}
                            {endpoint.exampleResponse && (
                              <div>
                                <h4 className="text-sm font-medium mb-2">
                                  {t("Example Response", "مثال على الاستجابة")}:
                                </h4>
                                <pre className="bg-muted p-4 rounded-lg text-sm font-mono overflow-x-auto">
                                  {endpoint.exampleResponse}
                                </pre>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="examples">
          <Card>
            <CardHeader>
              <CardTitle>{t("Code Examples", "أمثلة على الكود")}</CardTitle>
              <CardDescription>
                {t(
                  "Common API usage examples using different HTTP clients",
                  "أمثلة شائعة على استخدام API باستخدام عملاء HTTP مختلفين"
                )}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-8">
                <div>
                  <h3 className="text-lg font-semibold mb-4">
                    {t("Authentication Flow", "تدفق المصادقة")}
                  </h3>
                  <pre className="bg-muted p-4 rounded-lg text-sm font-mono overflow-x-auto">
{`// Login
const login = async (username, password) => {
  const response = await fetch('/api/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  });

  if (!response.ok) {
    throw new Error('Login failed');
  }

  return await response.json();
};

// Logout
const logout = async () => {
  await fetch('/api/logout', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' }
  });
};`}
                  </pre>
                </div>

                <div>
                  <h3 className="text-lg font-semibold mb-4">
                    {t("Sending Notifications", "إرسال الإشعارات")}
                  </h3>
                  <pre className="bg-muted p-4 rounded-lg text-sm font-mono overflow-x-auto">
{`// Using async/await
const sendNotification = async ({ title, body, url }) => {
  try {
    const response = await fetch('/api/notifications/send', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer <your_token>'
      },
      body: JSON.stringify({ title, body, url })
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message);
    }

    return await response.json();
  } catch (error) {
    console.error('Failed to send notification:', error);
    throw error;
  }
};

// Using axios
import axios from 'axios';

const sendNotificationWithAxios = async ({ title, body, url }) => {
  try {
    const response = await axios.post('/api/notifications/send', 
      { title, body, url },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer <your_token>'
        }
      }
    );
    return response.data;
  } catch (error) {
    console.error('Failed to send notification:', error.response?.data || error.message);
    throw error;
  }
};`}
                  </pre>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
        <TabsContent value="database">
          <Card>
            <CardHeader>
              <CardTitle>{t("Database Schema", "مخطط قاعدة البيانات")}</CardTitle>
              <CardDescription>
                {t(
                  "PostgreSQL database schema with Drizzle ORM",
                  "مخطط قاعدة بيانات PostgreSQL مع Drizzle ORM"
                )}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                <div>
                  <h3 className="text-lg font-semibold mb-2">users</h3>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`{
  id: serial("id").primaryKey(),
  username: text("username").notNull().unique(),
  password: text("password").notNull(),
  role: text("role").notNull().default("user"),
  isActive: boolean("is_active").notNull().default(true),
  createdAt: timestamp("created_at").defaultNow()
}`}
                  </pre>
                </div>

                <div>
                  <h3 className="text-lg font-semibold mb-2">events</h3>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`{
  id: serial("id").primaryKey(),
  title: text("title").notNull(),
  titleAr: text("title_ar").notNull(),
  description: text("description"),
  descriptionAr: text("description_ar"),
  startDate: timestamp("start_date").notNull(),
  endDate: timestamp("end_date").notNull(),
  createdAt: timestamp("created_at").defaultNow()
}`}
                  </pre>
                </div>

                <div>
                  <h3 className="text-lg font-semibold mb-2">sessions</h3>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`{
  id: serial("id").primaryKey(),
  eventId: integer("event_id").references(() => events.id),
  title: text("title").notNull(),
  titleAr: text("title_ar").notNull(),
  description: text("description"),
  descriptionAr: text("description_ar"),
  startTime: timestamp("start_time").notNull(),
  endTime: timestamp("end_time").notNull(),
  createdAt: timestamp("created_at").defaultNow()
}`}
                  </pre>
                </div>

                <div>
                  <h3 className="text-lg font-semibold mb-2">polls</h3>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`{
  id: serial("id").primaryKey(),
  title: text("title").notNull(),
  titleAr: text("title_ar").notNull(),
  description: text("description"),
  descriptionAr: text("description_ar"),
  eventId: integer("event_id").references(() => events.id),
  sessionId: integer("session_id").references(() => sessions.id),
  startDate: timestamp("start_date").notNull(),
  endDate: timestamp("end_date").notNull(),
  isActive: boolean("is_active").notNull().default(true),
  resultsPublished: boolean("results_published").notNull().default(false),
  createdAt: timestamp("created_at").defaultNow()
}`}
                  </pre>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="services">
          <Card>
            <CardHeader>
              <CardTitle>{t("External Services", "الخدمات الخارجية")}</CardTitle>
              <CardDescription>
                {t(
                  "Integration details for external services and APIs",
                  "تفاصيل التكامل مع الخدمات وواجهات البرمجة الخارجية"
                )}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                <div>
                  <h3 className="text-lg font-semibold mb-2">RTMP Server</h3>
                  <p className="text-sm text-muted-foreground mb-2">
                    {t("Used for live audio/video streaming", "يستخدم للبث المباشر للصوت والفيديو")}
                  </p>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`Server Configuration:
- Port: 1935 (RTMP)
- Port: 8000 (HTTP)

Stream URL Format:
- Test Stream: rtmp://[server-url]/live/test-stream
- Session Stream: rtmp://[server-url]/live/session_[id]

Example:
rtmp://your-app.example.com/live/session_1

Supported Streaming Software:
- OBS Studio
- Streamlabs
- XSplit`}
                  </pre>
                </div>

                <div>
                  <h3 className="text-lg font-semibold mb-2">OpenAI</h3>
                  <p className="text-sm text-muted-foreground mb-2">
                    {t("Used for AI chatbot and transcription", "يستخدم للدردشة الآلية والنسخ")}
                  </p>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`Models Used:
- gpt-4o (Latest model, May 2024)
  - Used for: Chatbot responses
  - Context window: Up to 128k tokens

- whisper-1
  - Used for: Audio transcription
  - Languages: Multilingual support
  - Real-time processing`}
                  </pre>
                </div>

                <div>
                  <h3 className="text-lg font-semibold mb-2">Deepgram</h3>
                  <p className="text-sm text-muted-foreground mb-2">
                    {t("Used for real-time audio transcription", "يستخدم للنسخ المباشر للصوت")}
                  </p>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`Features:
- Real-time transcription
- Multiple language support
- Speaker diarization
- Punctuation and formatting
- Custom vocabulary support`}
                  </pre>
                </div>
                <div>
                  <h3 className="text-lg font-semibold mb-2">SendGrid Email Service</h3>
                  <p className="text-sm text-muted-foreground mb-2">
                    {t("Used for sending transactional emails and notifications", "يستخدم لإرسال رسائل البريد الإلكتروني والإشعارات")}
                  </p>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`Configuration:
- API Version: v3
- From Email: Set via SENDGRID_FROM_EMAIL env var
- Templates: Dynamic templates supported
- Features:
  - User activation emails
  - Password reset notifications
  - Custom email templates
  - HTML and plain text support
  - Template variables
  - Tracking and analytics

Example Template Variables:
[Name] - User's full name
[ACTIVATION_LINK] - Account activation URL
[Event Name] - Event name/title`}
                  </pre>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="auth">
          <Card>
            <CardHeader>
              <CardTitle>{t("Authentication Guide", "دليل المصادقة")}</CardTitle>
              <CardDescription>
                {t(
                  "Learn how to authenticate your requests to access protected endpoints.",
                  "تعرف على كيفية مصادقة طلباتك للوصول إلى نقاط النهاية المحمية."
                )}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">{t("Session-based Auth", "المصادقة المستندة إلى الجلسة")}</h3>
                <p>
                  {t(
                    "The API uses session-based authentication. First, make a POST request to /api/login with your credentials to obtain a session cookie. This cookie will be automatically included in subsequent requests.",
                    "يستخدم API المصادقة المستندة إلى الجلسة. أولاً، قم بإرسال طلب POST إلى /api/login مع بيانات اعتمادك للحصول على ملف تعريف ارتباط الجلسة. سيتم تضمين ملف تعريف الارتباط هذا تلقائياً في الطلبات اللاحقة."
                  )}
                </p>

                <div className="mt-4">
                  <h4 className="font-medium mb-2">{t("Example Login Request", "مثال على طلب تسجيل الدخول")}</h4>
                  <pre className="bg-muted p-2 rounded text-xs">
                    {`POST /api/login
Content-Type: application/json

{
  "username": "your_username",
  "password": "your_password"
}`}
                  </pre>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}