import React, { Suspense, useCallback, useState, useMemo } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { 
  ArrowLeft, 
  Share2, 
  Printer, 
  Filter,
  Calendar,
  Users,
  BarChart3,
  PieChart,
  TrendingUp,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  Eye,
  RefreshCw, Download, FileText, FileSpreadsheet,
} from "lucide-react";
import { TaleLoadingFallback } from "@components/TaleLoadingFallback";
import { surveysService } from "@/api/surveys";
import SurveyResponsesStats from "./SurveyResponsesStats";
import { TaleRadio } from "@components/TaleRadio";
import { TaleInput } from "@components/TaleInput";
import TaleButton from "@components/TaleButton";
import { useTranslation } from "@/hooks/useTranslation";

// Mock data for enhanced analytics (you would replace with real API data)
const MOCK_ANALYTICS = {
  completionRate: 78,
  avgCompletionTime: "4m 32s",
  dropoutRate: 22,
  dailyResponses: [45, 52, 48, 55, 60, 58, 52, 65, 70, 68, 72, 75, 78, 80, 82],
  deviceBreakdown: [
    { device: 'Mobile', percentage: 65, color: '#00BDA9' },
    { device: 'Desktop', percentage: 25, color: '#3B82F6' },
    { device: 'Tablet', percentage: 10, color: '#8B5CF6' },
  ],
  topLocations: [
    { location: 'United States', responses: 245, percentage: 35 },
    { location: 'United Kingdom', responses: 128, percentage: 18 },
    { location: 'Germany', responses: 89, percentage: 13 },
    { location: 'France', responses: 67, percentage: 10 },
    { location: 'Others', responses: 171, percentage: 24 },
  ]
};

const SurveyAnalyticsPage = () => {
  const { t } = useTranslation();
  const { surveyId } = useParams();
  const navigate = useNavigate();
  const [dateRange, setDateRange] = useState("30d");
//   const [exporting, setExporting] = useState(false);
  const [showExportModal, setShowExportModal] = useState(false);
  const [exportFormat, setExportFormat] = useState("csv");
  const [exportCount, setExportCount] = useState("all");
  const [totalItems, setTotalItems] = useState(0);
  const [loadingTotal, setLoadingTotal] = useState(false);
  const [exporting, setExporting] = useState(false);

  const {
    isPending: loading,
    data: surveyData,
    error,
    refetch,
  } = useQuery({
    queryKey: ["survey-analytics", surveyId, dateRange],
    queryFn: async () => {
      try {
        const data = await surveysService.getSurvey(surveyId);
        // You would typically fetch analytics data here
        return {
          ...data,
          analytics: MOCK_ANALYTICS // Replace with actual API call
        };
      } catch (error) {
        throw new Error(error.message || "Failed to load survey analytics");
      }
    },
    retry: false,
  });

  const { data: responsesData } = useQuery({
    queryKey: ["survey-question-responses", surveyId],
    queryFn: () => surveysService.getUserResponsesToSurveyQuestions({ surveyId }),
    enabled: !!surveyId,
  });

  const { data: allResponsesData } = useQuery({
    queryKey: ["survey-results-paginated", surveyId],
    queryFn: () => surveysService.getSurveyResultsPaginated(surveyId, 0, 6),
    enabled: !!surveyId,
  });

  const handleBack = useCallback(() => {
    navigate(`/surveys`);
  }, [navigate, surveyId]);

  const handleExportClick = () => {
    setShowExportModal(true);
    fetchTotalItems();
  };

  const fetchTotalItems = async () => {
    setLoadingTotal(true);
    try {
      const data = await surveysService.getSurveyResultsPaginated(surveyId, 0, 1);
      // The API returns { result: [...], totalItems, currentPage, totalPages }
      setTotalItems(data.totalItems || 0);
    } catch (err) {
      console.error("Failed to fetch total responses count", err);
      setTotalItems(0);
    } finally {
      setLoadingTotal(false);
    }
  };

  const exportToCSV = (data, filename) => {
    if (!data.length) return;
    const headers = Object.keys(data[0]);
    const csvRows = [];

    // Quote headers exactly like values to prevent comma-splitting
    csvRows.push(headers.map(h => `"${String(h).replace(/"/g, '""')}"`).join(","));

    for (const row of data) {
      const values = headers.map(header => {
        const val = row[header] ?? "";
        return `"${String(val).replace(/"/g, '""')}"`;
      });
      csvRows.push(values.join(","));
    }

    const blob = new Blob([csvRows.join("\n")], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.href = url;
    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const exportToPDF = (data, filename) => {
    if (!data.length) return;
    const win = window.open();

    const COLS_PER_ROW = 5;

    // Separate metadata keys from question keys
    const metaKeys = ["Response ID", "User", "Finished At"];
    const questionKeys = Object.keys(data[0]).filter(k => !metaKeys.includes(k));

    // Split question keys into chunks of COLS_PER_ROW
    const chunks = [];
    for (let i = 0; i < questionKeys.length; i += COLS_PER_ROW) {
      chunks.push(questionKeys.slice(i, i + COLS_PER_ROW));
    }

    const rows = data.map((row) => {
      const meta = `
      <tr style="background:#f9f9f9;">
        <td colspan="${COLS_PER_ROW}" style="padding:8px; border:1px solid #ddd; font-weight:bold; font-size:12px;">
          <span style="margin-right:16px;">Response ID: <strong>${row["Response ID"]}</strong></span>
          <span style="margin-right:16px;">User: <strong>${row["User"]}</strong></span>
          <span>Finished At: <strong>${row["Finished At"]}</strong></span>
        </td>
      </tr>
    `;

      const questionRows = chunks.map((chunk) => {
        const headers = chunk.map(k => `<th style="border:1px solid #ddd; padding:6px; background:#f2f2f2; font-size:11px; word-break:break-word;">${k}</th>`).join("");
        const filledChunk = [...chunk];
        while (filledChunk.length < COLS_PER_ROW) filledChunk.push(null);
        const cells = filledChunk.map(k =>
            `<td style="border:1px solid #ddd; padding:6px; font-size:11px; word-break:break-word;">${k ? (row[k] ?? "") : ""}</td>`
        ).join("");
        return `
        <tr><th colspan="${COLS_PER_ROW}" style="border:none; padding:0;">
          <table style="width:100%; border-collapse:collapse; table-layout:fixed;">
            <thead><tr>${headers}</tr></thead>
            <tbody><tr>${cells}</tr></tbody>
          </table>
        </th></tr>
      `;
      }).join("");

      return meta + questionRows;
    }).join(`<tr><td colspan="${COLS_PER_ROW}" style="height:12px; border:none;"></td></tr>`);

    win.document.write(`
    <html>
      <head><title>${filename}</title>
      <style>
        body { font-family: Arial, sans-serif; margin: 20px; font-size: 12px; }
        h2 { font-size: 16px; margin-bottom: 16px; }
        table { border-collapse: collapse; width: 100%; table-layout: fixed; }
        th, td { word-break: break-word; }
        @media print { body { margin: 10px; } }
      </style>
      </head>
      <body>
        <h2>${filename}</h2>
        <table>
          <tbody>${rows}</tbody>
        </table>
      </body>
    </html>
  `);
    win.document.close();
    win.print();
  };

  const getAnswerText = (answerValue, optionsArray) => {
    if (!Array.isArray(optionsArray) || optionsArray.length === 0) return answerValue;

    // Strip letter prefix like "a.\t", "b.\t" from each option
    const optionTexts = optionsArray.map(o => o.replace(/^[a-zA-Z]\.\t/, "").trim());

    // Handle checkbox (array of indices)
    if (typeof answerValue === "string" && answerValue.startsWith("[") && answerValue.endsWith("]")) {
      try {
        const indices = JSON.parse(answerValue);
        if (Array.isArray(indices)) {
          return indices.map(idx => optionTexts[idx]).filter(Boolean).join(", ");
        }
      } catch (e) { /* fall through */ }
    }

    // Single selection
    const index = parseInt(answerValue, 10);
    if (!isNaN(index) && optionTexts[index] !== undefined) {
      return optionTexts[index];
    }

    return answerValue;
  };

  const handleExportConfirm = async () => {
    setExporting(true);
    try {
      let limit = totalItems;
      if (exportCount !== "all") {
        limit = Math.min(parseInt(exportCount, 10), totalItems);
      }
      if (limit <= 0) {
        alert(t("surveyBuilder.analyticsPage.noResponsesToExport"));
        return;
      }

      const RESPONSES_PER_FILE = 100;
      const pagesNeeded = Math.ceil(limit / RESPONSES_PER_FILE);
      const filename = `${surveyData?.title || "survey"}_responses_${new Date().toISOString().slice(0, 19)}`;

      for (let page = 0; page < pagesNeeded; page++) {
        const size = Math.min(RESPONSES_PER_FILE, limit - page * RESPONSES_PER_FILE);
        const data = await surveysService.getSurveyResultsPaginated(surveyId, page, size);
        const responses = data.result || [];

        // Build one row per response with dynamic question columns
        const allRows = responses.map((resp) => {
          let finishedAtStr = "";
          if (Array.isArray(resp.finishedAt)) {
            const [year, month, day, hour, minute, second] = resp.finishedAt;
            finishedAtStr = new Date(year, month - 1, day, hour, minute, second).toLocaleString();
          } else {
            finishedAtStr = resp.finishedAt || "";
          }

          const row = {
            "Response ID": resp.responseId,
            "User": resp.userName || "Anonymous",
            "Finished At": finishedAtStr,
          };

          for (const ans of resp.answers || []) {
            row[ans.questionText.trim()] = getAnswerText(ans.answerValue, ans.options);
          }

          return row;
        });

        if (!allRows.length) continue;

        const fileLabel = pagesNeeded > 1 ? `${filename}_part${page + 1}` : filename;
        if (exportFormat === "csv") {
          exportToCSV(allRows, `${fileLabel}.csv`);
        } else {
          exportToPDF(allRows, fileLabel);
        }

        // Small delay between file downloads to avoid browser blocking
        if (page < pagesNeeded - 1) {
          await new Promise(r => setTimeout(r, 500));
        }
      }

      setShowExportModal(false);
    } catch (err) {
      console.error("Export failed:", err);
      alert(t("surveyBuilder.analyticsPage.exportFailed"));
    } finally {
      setExporting(false);
    }
  };

  const handleShare = async () => {
    const shareData = {
      title: t("surveyBuilder.analyticsPage.shareTitle", { title: surveyData?.title }),
      text: t("surveyBuilder.analyticsPage.shareText", { title: surveyData?.title }),
      url: window.location.href,
    };

    if (navigator.share && navigator.canShare(shareData)) {
      try {
        await navigator.share(shareData);
      } catch (err) {
        console.log('Share cancelled or failed');
      }
    } else {
      await navigator.clipboard.writeText(window.location.href);
      // Show toast notification
      alert(t("surveyBuilder.analyticsPage.linkCopied"));
    }
  };

//   const handleExport = async (format = 'pdf') => {
//     setExporting(true);
//     try {
//       // Implement export functionality
//       await new Promise(resolve => setTimeout(resolve, 1500)); // Mock API call
//       alert(`Report exported successfully as ${format.toUpperCase()}`);
//     } catch (error) {
//       alert("Failed to export report");
//     } finally {
//       setExporting(false);
//     }
//   };

  const getDateRangeLabel = useMemo(() => {
    const ranges = {
      '7d': t("surveyBuilder.analyticsPage.dateRange7d"),
      '30d': t("surveyBuilder.analyticsPage.dateRange30d"),
      '90d': t("surveyBuilder.analyticsPage.dateRange90d"),
      'all': t("surveyBuilder.analyticsPage.dateRangeAll"),
    };
    return ranges[dateRange] || ranges['30d'];
  }, [dateRange, t]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50/30 p-4 md:p-8">
        <TaleLoadingFallback className="py-20" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50/30 p-4 md:p-8 flex items-center justify-center">
        <div className="text-center max-w-md bg-white rounded-2xl shadow-lg p-8">
          <div className="w-20 h-20 mx-auto mb-6 bg-red-100 rounded-full flex items-center justify-center">
            <AlertCircle className="h-10 w-10 text-red-600" />
          </div>
          <h2 className="text-2xl font-bold text-gray-900 mb-2">{t("surveyBuilder.analyticsPage.unableToLoad")}</h2>
          <p className="text-gray-600 mb-6">{error.message}</p>
          <div className="flex gap-3 justify-center">
            <button
              onClick={handleBack}
              className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors shadow-md"
            >
              {t("surveyBuilder.completed.returnToSurvey")}
            </button>
            <button
              onClick={() => refetch()}
              className="px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
            >
              {t("surveyBuilder.analyticsPage.tryAgain")}
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br to-blue-50/30 rounded-lg">
      {/* Print styles */}
      <style>
        {`
          @media print {
            .no-print {
              display: none !important;
            }
            .print-full-width {
              width: 100% !important;
              max-width: 100% !important;
            }
            .print-grid {
              break-inside: avoid;
            }
          }
        `}
      </style>

      {/* Header */}
      <header className="bg-[#EFEFEF] rounded-2xl backdrop-blur-sm border-b shadow-sm top-0 z-50 print:border-none">
        <div className="mx-auto bg-white rounded-2xl px-4 sm:px-6 lg:px-8">
          <div className="flex flex-col md:flex-row md:items-center justify-between py-4 gap-4">
            <div className="flex items-center gap-4">
              <button
                onClick={handleBack}
                className="no-print flex items-center justify-center w-10 h-10 rounded-lg hover:bg-gray-100 transition-colors group"
                aria-label={t("surveyBuilder.step4.goBackAlt")}
              >
                <ArrowLeft className="h-5 w-5 text-gray-600 group-hover:text-blue-600 transition-colors rtl:-scale-x-100" />
              </button>
              
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-xl bg-tale-business from-blue-500 to-blue-600">
                  <BarChart3 className="h-6 w-6 text-white" />
                </div>
                <div>
                  <h1 className="text-xl md:text-2xl font-bold text-gray-900">
                    {surveyData?.title}
                  </h1>
                  <p className="text-gray-600 text-sm mt-1 flex items-center gap-2">
                    <span>{t("surveyBuilder.analyticsPage.analyticsDashboard")}</span>
                    <span className="text-xs px-2 py-1 bg-blue-100 text-blue-800 rounded-full">
                      {getDateRangeLabel}
                    </span>
                  </p>
                </div>
              </div>
            </div>
            
            <div className="flex items-center gap-3 no-print">
              <div className="flex items-center gap-3">
                <div className="relative group">
                  <button
                    onClick={() => setDateRange(dateRange === '30d' ? '90d' : '30d')}
                    className="flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-200 hover:bg-gray-50 transition-colors"
                  >
                    <Calendar className="h-4 w-4 text-gray-500" />
                    <span className="text-sm font-medium">{getDateRangeLabel}</span>
                  </button>
                  <div className="absolute hidden group-hover:block top-full mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 p-2 z-10">
                    {['7d', '30d', '90d', 'all'].map((range) => (
                      <button
                        key={range}
                        onClick={() => setDateRange(range)}
                        className={`w-full text-left px-3 py-2 rounded text-sm hover:bg-gray-50 ${
                          dateRange === range ? 'bg-blue-50 text-blue-600 font-medium' : 'text-gray-700'
                        }`}
                      >
                        {range === '7d' ? t("surveyBuilder.analyticsPage.dateRange7d") :
                         range === '30d' ? t("surveyBuilder.analyticsPage.dateRange30d") :
                         range === '90d' ? t("surveyBuilder.analyticsPage.dateRange90d") : t("surveyBuilder.analyticsPage.dateRangeAll")}
                      </button>
                    ))}
                  </div>
                </div>
                
                <button
                  onClick={handleShare}
                  className="p-2 rounded-lg hover:bg-gray-100 transition-colors group"
                  aria-label={t("surveyBuilder.analyticsPage.shareReportAria")}
                >
                  <Share2 className="h-5 w-5 text-gray-600 group-hover:text-blue-600 transition-colors" />
                </button>

                <button
                  onClick={handleExportClick}
                  className="p-2 rounded-lg hover:bg-gray-100 transition-colors group"
                  aria-label={t("surveyBuilder.analyticsPage.printReportAria")}
                >
                  <Printer className="h-5 w-5 text-gray-600 group-hover:text-blue-600 transition-colors" />
                </button>
                
                {/* <div className="relative group">
                  <button
                    disabled={exporting}
                    className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg hover:from-blue-700 hover:to-blue-800 transition-all shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {exporting ? (
                      <RefreshCw className="h-4 w-4 animate-spin" />
                    ) : (
                      <Download className="h-4 w-4" />
                    )}
                    {exporting ? 'Exporting...' : 'Export'}
                  </button>
                  <div className="absolute hidden group-hover:block top-full mt-2 right-0 w-40 bg-white rounded-lg shadow-lg border border-gray-200 p-2 z-10">
                    <button
                      onClick={() => handleExport('pdf')}
                      className="w-full text-left px-3 py-2 rounded text-sm hover:bg-gray-50 text-gray-700"
                    >
                      Export as PDF
                    </button>
                    <button
                      onClick={() => handleExport('excel')}
                      className="w-full text-left px-3 py-2 rounded text-sm hover:bg-gray-50 text-gray-700"
                    >
                      Export as Excel
                    </button>
                    <button
                      onClick={() => handleExport('csv')}
                      className="w-full text-left px-3 py-2 rounded text-sm hover:bg-gray-50 text-gray-700"
                    >
                      Export as CSV
                    </button>
                  </div>
                </div> */}
              </div>
            </div>
          </div>
          
          {/* Survey Stats Bar */}
          <div className="pb-4 no-print">
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              <div className="bg-white rounded-xl p-4 border border-gray-200 shadow-sm">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 font-medium">{t("surveyBuilder.analyticsPage.totalResponsesLabel")}</p>
                    <p className="text-2xl font-bold text-gray-900 mt-1">{surveyData?.responsesNumber || 0}</p>
                  </div>
                  <Users className="h-8 w-8 text-blue-500" />
                </div>
              </div>
              
              <div className="bg-white rounded-xl p-4 border border-gray-200 shadow-sm">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 font-medium">{t("surveyBuilder.analyticsPage.completionRateLabel")}</p>
                    <p className="text-2xl font-bold text-gray-900 mt-1">{surveyData?.analytics?.completionRate || 0}%</p>
                  </div>
                  <CheckCircle className="h-8 w-8 text-green-500" />
                </div>
              </div>
              
              <div className="bg-white rounded-xl p-4 border border-gray-200 shadow-sm">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 font-medium">{t("surveyBuilder.analyticsPage.avgTimeLabel")}</p>
                    <p className="text-2xl font-bold text-gray-900 mt-1">{surveyData?.analytics?.avgCompletionTime || 'N/A'}</p>
                  </div>
                  <Clock className="h-8 w-8 text-purple-500" />
                </div>
              </div>
              
              <div className="bg-white rounded-xl p-4 border border-gray-200 shadow-sm">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 font-medium">{t("surveyBuilder.analyticsPage.dropoutRateLabel")}</p>
                    <p className="text-2xl font-bold text-gray-900 mt-1">{surveyData?.analytics?.dropoutRate || 0}%</p>
                  </div>
                  <XCircle className="h-8 w-8 text-red-500" />
                </div>
              </div>
              
              <div className="bg-white rounded-xl p-4 border border-gray-200 shadow-sm">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 font-medium">{t("surveyBuilder.detail.statusLabel")}</p>
                    <p className="text-xl font-bold mt-1">
                      <span className={`px-2 py-1 rounded-full text-sm font-medium ${
                        surveyData?.status === 'COMPLETED' 
                          ? 'bg-green-100 text-green-800'
                          : surveyData?.status === 'IN_PROGRESS'
                          ? 'bg-yellow-100 text-yellow-800'
                          : 'bg-gray-100 text-gray-800'
                      }`}>
                        {surveyData?.status}
                      </span>
                    </p>
                  </div>
                  <TrendingUp className="h-8 w-8 text-amber-500" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Export Modal */}
      {showExportModal && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
            <div className="bg-white rounded-2xl shadow-xl w-full max-w-md p-6">
              <div className="flex items-center justify-between mb-6 border-b pb-4">
                <h3 className="text-lg font-semibold text-gray-900">{t("surveyBuilder.analyticsPage.exportResponsesTitle")}</h3>
                <button onClick={() => setShowExportModal(false)} className="text-gray-400 hover:text-gray-600 text-xl leading-none">
                  &times;
                </button>
              </div>

              <div className="flex flex-col gap-5">
                {/* Format selection */}
                <div className="flex flex-col gap-2">
                  <span className="font-semibold text-sm">{t("surveyBuilder.analyticsPage.formatLabel")}</span>
                  <div className="flex gap-6">
                    <TaleRadio
                        role="normal"
                        checked={exportFormat === "csv"}
                        onChange={() => setExportFormat("csv")}
                        label={
                          <div className="flex items-center gap-2">
                            <FileSpreadsheet className="w-4 h-4" />
                            CSV
                          </div>
                        }
                    />
                    <TaleRadio
                        role="normal"
                        checked={exportFormat === "pdf"}
                        onChange={() => setExportFormat("pdf")}
                        label={
                          <div className="flex items-center gap-2">
                            <FileText className="w-4 h-4" />
                            PDF
                          </div>
                        }
                    />
                  </div>
                </div>

                {/* Number of responses */}
                <div className="flex flex-col gap-2">
                  <span className="font-semibold text-sm">{t("surveyBuilder.analyticsPage.numberOfResponsesLabel")}</span>
                  {loadingTotal ? (
                      <div className="text-sm text-gray-500">{t("surveyBuilder.analyticsPage.loadingTotalCount")}</div>
                  ) : (
                      <div className="flex flex-col gap-3">
                        <TaleRadio
                            role="normal"
                            checked={exportCount === "all"}
                            onChange={() => setExportCount("all")}
                            label={t("surveyBuilder.analyticsPage.allCount", { count: totalItems })}
                        />
                        <div className="flex items-center gap-3">
                          <TaleRadio
                              role="normal"
                              checked={exportCount !== "all"}
                              onChange={() => setExportCount("100")}
                              label={t("surveyBuilder.analyticsPage.customLabel")}
                          />
                          <TaleInput
                              type="number"
                              className="w-28"
                              placeholder="100"
                              value={exportCount === "all" ? "" : exportCount}
                              onChange={(e) => setExportCount(e.target.value)}
                              disabled={exportCount === "all"}
                              min={1}
                              max={totalItems}
                          />
                        </div>
                      </div>
                  )}
                  {totalItems > 100 && (
                      <p className="text-xs text-gray-500 mt-1">
                        {t("surveyBuilder.analyticsPage.exportSplitNote")}
                      </p>
                  )}
                </div>
              </div>

              <div className="flex justify-end gap-3 mt-6 pt-4 border-t">
                <TaleButton
                    variant="outlined"
                    role="normal"
                    onClick={() => setShowExportModal(false)}
                    disabled={exporting}
                >
                  {t("common.cancel")}
                </TaleButton>
                <TaleButton
                    role="normal"
                    onClick={handleExportConfirm}
                    disabled={exporting || loadingTotal || totalItems === 0}
                    loading={exporting}
                >
                  <div className="flex items-center gap-2">
                    {!exporting && <Download className="w-4 h-4" />}
                    {exporting ? t("surveyBuilder.analyticsPage.exportingLabel") : t("surveyBuilder.analyticsPage.exportLabel")}
                  </div>
                </TaleButton>
              </div>
            </div>
          </div>
      )}

      {/* Main Content */}
      <main className="mx-auto md:py-4 bg-[#EFEFEF]">
        <div className="print-full-width">
          {/* Dashboard Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            {/* Left Column - Main Stats */}
            <div className="lg:col-span-2 space-y-6 print-grid">
              <div className="bg-white rounded-2xl  border-gray-200 shadow-sm p-6">
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-lg font-bold text-gray-900">{t("surveyBuilder.analyticsPage.responseTrendsTitle")}</h2>
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    <Filter className="h-4 w-4" />
                    <span>{t("surveyBuilder.analyticsPage.dailyResponsesLabel")}</span>
                  </div>
                </div>
                {/* This would be a chart component */}
                <div className="h-64 relative">
                  <div className="absolute inset-0 flex items-end gap-1">
                    {surveyData?.analytics?.dailyResponses?.map((value, index) => (
                      <div 
                        key={index}
                        className="flex-1 bg-gradient-to-t from-[#00BDA9] to-[#00C0FC] rounded-t-lg transition-all hover:from-[#00BD85] hover:to-[#00C0FF]"
                        style={{ height: `${value}%` }}
                        title={t("surveyBuilder.analyticsPage.responsesCountTitle", { count: value })}
                      />
                    ))}
                  </div>
                  <div className="absolute bottom-0 left-0 right-0 h-px bg-gray-200"></div>
                </div>
              </div>

              {/* Quick Overview Section */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="bg-white from-blue-50 to-blue-100/50 rounded-2xl border-gray-200 p-6">
                  <h3 className="text-lg font-bold text-gray-900 mb-4">{t("surveyBuilder.analyticsPage.deviceBreakdownTitle")}</h3>
                  <div className="space-y-4">
                    {surveyData?.analytics?.deviceBreakdown?.map((item, index) => (
                      <div key={index} className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div 
                            className="w-3 h-3 rounded-full"
                            style={{ backgroundColor: item.color }}
                          />
                          <span className="text-sm font-medium text-gray-700">{item.device}</span>
                        </div>
                        <div className="text-right">
                          <span className="font-bold text-gray-900">{item.percentage}%</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="bg-white from-teal-50 to-teal-100/50 rounded-2xl border-gray-200 p-6">
                  <h3 className="text-lg font-bold text-gray-900 mb-4">{t("surveyBuilder.analyticsPage.topLocationsTitle")}</h3>
                  <div className="space-y-4">
                    {surveyData?.analytics?.topLocations?.slice(0, 3).map((item, index) => (
                      <div key={index} className="flex items-center justify-between">
                        <span className="text-sm font-medium text-gray-700">{item.location}</span>
                        <div className="flex items-center gap-3">
                          <div className="w-24 h-2 bg-gray-200 rounded-full overflow-hidden">
                            <div 
                              className="h-full bg-teal-500 rounded-full"
                              style={{ width: `${item.percentage}%` }}
                            />
                          </div>
                          <span className="text-sm font-bold text-gray-900">{item.responses}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Right Column - Insights & Actions */}
            <div className="space-y-6 print-grid">
              <div className="bg-white rounded-2xl border-gray-200 shadow-sm p-6">
                <h3 className="text-lg font-bold text-gray-900 mb-4">{t("surveyBuilder.analyticsPage.quickInsightsTitle")}</h3>
                <div className="space-y-4">
                  <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                    <Eye className="h-5 w-5 text-blue-500 mt-0.5" />
                    <div>
                      <p className="text-sm font-medium text-gray-900">{t("surveyBuilder.analyticsPage.surveyPerformanceLabel")}</p>
                      <p className="text-xs text-gray-600 mt-1">
                        {t("surveyBuilder.analyticsPage.surveyPerformanceText", { rate: surveyData?.analytics?.completionRate })}
                      </p>
                    </div>
                  </div>

                  <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                    <TrendingUp className="h-5 w-5 text-green-500 mt-0.5" />
                    <div>
                      <p className="text-sm font-medium text-gray-900">{t("surveyBuilder.analyticsPage.responseGrowthLabel")}</p>
                      <p className="text-xs text-gray-600 mt-1">
                        {t("surveyBuilder.analyticsPage.responseGrowthText")}
                      </p>
                    </div>
                  </div>

                  <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                    <AlertCircle className="h-5 w-5 text-amber-500 mt-0.5" />
                    <div>
                      <p className="text-sm font-medium text-gray-900">{t("surveyBuilder.analyticsPage.attentionNeededLabel")}</p>
                      <p className="text-xs text-gray-600 mt-1">
                        {t("surveyBuilder.analyticsPage.attentionNeededText")}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              <div className="bg-white from-purple-50 to-purple-100/50 rounded-2xl border-gray-200 p-6">
                <h3 className="text-lg font-bold text-gray-900 mb-4">{t("surveyBuilder.analyticsPage.recommendedActionsTitle")}</h3>
                <div className="space-y-3">
                  <button className="w-full text-left rtl:text-right p-3 bg-white rounded-lg border border-gray-200 hover:border-gray-300 hover:shadow-sm transition-all">
                    <p className="text-sm font-medium text-gray-900">{t("surveyBuilder.analyticsPage.actionFollowUpTitle")}</p>
                    <p className="text-xs text-gray-500 mt-1">{t("surveyBuilder.analyticsPage.actionFollowUpText")}</p>
                  </button>

                  <button className="w-full text-left rtl:text-right p-3 bg-white rounded-lg border border-gray-200 hover:border-gray-300 hover:shadow-sm transition-all">
                    <p className="text-sm font-medium text-gray-900">{t("surveyBuilder.analyticsPage.actionShareTitle")}</p>
                    <p className="text-xs text-gray-500 mt-1">{t("surveyBuilder.analyticsPage.actionShareText")}</p>
                  </button>

                  <button className="w-full text-left rtl:text-right p-3 bg-white rounded-lg border border-gray-200 hover:border-gray-300 hover:shadow-sm transition-all">
                    <p className="text-sm font-medium text-gray-900">{t("surveyBuilder.analyticsPage.actionDuplicateTitle")}</p>
                    <p className="text-xs text-gray-500 mt-1">{t("surveyBuilder.analyticsPage.actionDuplicateText")}</p>
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* Main Analytics Section */}
          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden print-grid">
            <div className="border-b border-gray-200">
              <div className="px-6 py-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <PieChart className="h-5 w-5 text-gray-700" />
                    <h2 className="text-xl font-bold text-gray-900">{t("surveyBuilder.analyticsPage.detailedAnalyticsTitle")}</h2>
                  </div>
                  <button
                    onClick={() => refetch()}
                    className="flex items-center gap-2 px-3 py-2 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition-colors"
                  >
                    <RefreshCw className="h-4 w-4" />
                    {t("surveyBuilder.analyticsPage.refreshData")}
                  </button>
                </div>
                <p className="text-gray-600 text-sm mt-2">
                  {t("surveyBuilder.analyticsPage.comprehensiveAnalysisText")}
                </p>
              </div>
            </div>
            
            <div className="p-6">
              <Suspense fallback={
                <div className="py-12">
                  <TaleLoadingFallback />
                </div>
              }>
                <SurveyResponsesStats 
                  surveyData={surveyData} 
                  responsesData={responsesData}
                  allResponsesData={allResponsesData}
                />
              </Suspense>
            </div>
          </div>

          {/* Footer Notes */}
          <div className="mt-6 text-center text-sm text-gray-500 no-print">
            <p>
              {t("surveyBuilder.analyticsPage.dataLastUpdated", { date: new Date().toLocaleDateString(), time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) })}
            </p>
            <p className="mt-1">
              {t("surveyBuilder.analyticsPage.autoUpdateNote")}
            </p>
          </div>
        </div>
      </main>
    </div>
  );
};

export default SurveyAnalyticsPage;