import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import { Search, Download, Calendar, Filter, ChevronRight, Phone, Clock, CheckCircle, XCircle, Loader2 } from "lucide-react";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { ExportModal, ExportFormat } from "./ExportModal";
import { exportCallLogs } from "@/lib/exportUtils";
import { useTranslation } from "react-i18next";
import { supabase } from "@/lib/supabase";
import { API_URL } from "@/lib/config";
import { LoadingScreen } from "@/components/ui/loading-screen";
import { AnalyticsStatus, ANALYTICS_STATUS } from "@/types/database.types";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

interface CallLog {
  id: string;
  store_id: string;
  created_at: string;
  started_at: string | null;
  ended_at: string | null;
  duration: number | null;
  caller: string | null;
  transcript: string | null;
  recording_url: string | null;
  costs: any | null;
  cost_total: number | null;
  payload: any;
  outcome: string | null;
  analytics_status: AnalyticsStatus | null;
  analytics_error: string | null;
}

// Analytics status indicator component
const AnalyticsStatusIndicator = ({ status, error, t }: { status: AnalyticsStatus | null; error: string | null; t: (key: string) => string }) => {
  if (!status || status === ANALYTICS_STATUS.PENDING) {
    return (
      <Tooltip>
        <TooltipTrigger>
          <Clock className="w-4 h-4 text-slate-400" />
        </TooltipTrigger>
        <TooltipContent>
          <p>{t('callLogs.analyticsStatus.pending')}</p>
        </TooltipContent>
      </Tooltip>
    );
  }

  if (status === ANALYTICS_STATUS.RUNNING) {
    return (
      <Tooltip>
        <TooltipTrigger>
          <Loader2 className="w-4 h-4 text-blue-400 animate-spin" />
        </TooltipTrigger>
        <TooltipContent>
          <p>{t('callLogs.analyticsStatus.running')}</p>
        </TooltipContent>
      </Tooltip>
    );
  }

  if (status === ANALYTICS_STATUS.COMPLETED) {
    return (
      <Tooltip>
        <TooltipTrigger>
          <CheckCircle className="w-4 h-4 text-green-400" />
        </TooltipTrigger>
        <TooltipContent>
          <p>{t('callLogs.analyticsStatus.completed')}</p>
        </TooltipContent>
      </Tooltip>
    );
  }

  if (status === ANALYTICS_STATUS.FAILED) {
    return (
      <Tooltip>
        <TooltipTrigger>
          <XCircle className="w-4 h-4 text-red-400" />
        </TooltipTrigger>
        <TooltipContent>
          <p>{t('callLogs.analyticsStatus.failed')}</p>
          {error && <p className="text-xs text-red-300 mt-1">{error}</p>}
        </TooltipContent>
      </Tooltip>
    );
  }

  return null;
};

const getOutcomeColor = (outcome: string | null): string => {
  if (!outcome) return "bg-slate-600";

  const colorMap: Record<string, string> = {
    resolved: "bg-green-600",
    order_placed: "bg-green-600",
    order_inquiry: "bg-blue-600",
    product_inquiry: "bg-blue-600",
    general_question: "bg-blue-600",
    complaint: "bg-red-600",
    return_request: "bg-orange-600",
    callback_requested: "bg-purple-600",
    escalated: "bg-yellow-600",
    no_answer: "bg-slate-500",
    voicemail: "bg-slate-500",
    wrong_number: "bg-slate-500",
    abandoned: "bg-slate-500",
  };

  return colorMap[outcome] || "bg-slate-600";
};

const formatOutcome = (outcome: string | null): string => {
  if (!outcome) return "-";
  return outcome.split('_').map(word =>
    word.charAt(0).toUpperCase() + word.slice(1)
  ).join(' ');
};

const formatDuration = (seconds: number | null): string => {
  if (!seconds) return "-";
  const mins = Math.floor(seconds / 60);
  const secs = Math.round(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, '0')}`;
};

const formatDateTime = (dateStr: string | null): string => {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  return date.toLocaleString();
};

export function CallLogsContent() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [isExportModalOpen, setIsExportModalOpen] = useState(false);
  const [callLogs, setCallLogs] = useState<CallLog[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");

  const fetchCallLogs = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        throw new Error('Not authenticated');
      }

      const response = await fetch(`${API_URL}/api/call-logs`, {
        headers: {
          'Authorization': `Bearer ${session.access_token}`,
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to fetch call logs');
      }

      const data = await response.json();
      setCallLogs(data.call_logs || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchCallLogs();
  }, []);

  const handleRowClick = (callId: string) => {
    navigate(`/call-logs/${callId}`);
  };

  const handleExportClick = () => {
    setIsExportModalOpen(true);
  };

  const handleCloseExportModal = () => {
    setIsExportModalOpen(false);
  };

  const handleExport = (format: ExportFormat) => {
    const timestamp = new Date().toISOString().split('T')[0];
    const filename = `call-logs-${timestamp}`;
    const exportData = callLogs.map(log => ({
      time: log.started_at || log.created_at,
      caller: log.caller || '',
      duration: formatDuration(log.duration),
      // cost hidden - cost calculation not fully implemented
      // cost: log.cost_total ? `$${log.cost_total.toFixed(4)}` : '',
    }));
    exportCallLogs(exportData, format, filename);
  };

  const filteredLogs = callLogs.filter(log => {
    if (!searchQuery) return true;
    const searchLower = searchQuery.toLowerCase();
    return (
      (log.caller && log.caller.toLowerCase().includes(searchLower)) ||
      (log.transcript && log.transcript.toLowerCase().includes(searchLower)) ||
      (log.outcome && formatOutcome(log.outcome).toLowerCase().includes(searchLower))
    );
  });

  return (
    <>
      <div className="flex-1 bg-slate-900 text-white">
        {/* Header */}
        <div className="border-b border-slate-800 bg-slate-900">
          <div className="flex items-center justify-between p-6">
            <div>
              <h1 className="text-2xl font-semibold text-white">{t('callLogs.title')}</h1>
              <p className="text-slate-400">{t('callLogs.subtitle')}</p>
            </div>

            <div className="flex items-center gap-4">
              <Button
                className="bg-slate-700 hover:bg-slate-600 text-white"
                onClick={handleExportClick}
                disabled={isLoading || callLogs.length === 0}
              >
                <Download className="w-4 h-4 mr-2" />
                {t('callLogs.export')}
              </Button>

              <Button className="bg-slate-700 hover:bg-slate-600 text-white">
                <Calendar className="w-4 h-4 mr-2" />
                {t('callLogs.dateRange')}
              </Button>
            </div>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="p-6 border-b border-slate-800">
          <div className="flex items-center gap-4">
            <div className="relative flex-1 max-w-lg">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
              <Input
                placeholder={t('callLogs.searchPlaceholder')}
                className="pl-10 bg-slate-800 border-slate-700 text-white placeholder-slate-400"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>

            <Button variant="outline" className="bg-slate-800 border-slate-700 text-slate-300 hover:text-white hover:bg-slate-700">
              <Filter className="w-4 h-4 mr-2" />
              {t('callLogs.filters')}
            </Button>
          </div>
        </div>

        {/* Call Logs Table */}
        <div className="p-6">
          <Card className="bg-slate-800 border-slate-700">
            <div className="p-6">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-semibold text-white">{t('callLogs.allCallLogs')}</h3>
                {!isLoading && !error && (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="text-slate-400 hover:text-white"
                    onClick={fetchCallLogs}
                  >
                    <svg className="w-4 h-4 mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M23 4v6h-6M1 20v-6h6" strokeLinecap="round" strokeLinejoin="round"/>
                      <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    {t('common.refresh')}
                  </Button>
                )}
              </div>

              {isLoading ? (
                <LoadingScreen
                  icon={Phone}
                  message={t('callLogs.loadingCallLogs')}
                  fullScreen={false}
                />
              ) : error ? (
                <div className="flex flex-col items-center justify-center py-12">
                  <div className="w-16 h-16 bg-red-500/10 rounded-full flex items-center justify-center mb-4">
                    <svg className="w-8 h-8 text-red-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <circle cx="12" cy="12" r="10"/>
                      <line x1="12" y1="8" x2="12" y2="12"/>
                      <line x1="12" y1="16" x2="12.01" y2="16"/>
                    </svg>
                  </div>
                  <p className="text-red-500 font-medium mb-2">{t('callLogs.failedToLoad')}</p>
                  <p className="text-slate-400 text-sm mb-4">{error}</p>
                  <Button
                    className="bg-slate-700 hover:bg-slate-600 text-white"
                    onClick={fetchCallLogs}
                  >
                    <svg className="w-4 h-4 mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M23 4v6h-6M1 20v-6h6" strokeLinecap="round" strokeLinejoin="round"/>
                      <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    {t('common.tryAgain')}
                  </Button>
                </div>
              ) : filteredLogs.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-12">
                  <p className="text-slate-400">{t('callLogs.noCalls')}</p>
                </div>
              ) : (
                <TooltipProvider>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-slate-700">
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.startedAt')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.endedAt')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.duration')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.caller')}</th>
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.outcome')}</th>
                        <th className="text-center py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.analytics')}</th>
                        {/* Cost column hidden - cost calculation not fully implemented
                        <th className="text-left py-3 px-4 text-sm font-medium text-slate-400">{t('callLogs.table.cost')}</th>
                        */}
                        <th className="text-right py-3 px-4 text-sm font-medium text-slate-400"></th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredLogs.map((call) => (
                        <tr
                          key={call.id}
                          className="border-b border-slate-700/50 hover:bg-slate-700/30 cursor-pointer transition-colors"
                          onClick={() => handleRowClick(call.id)}
                        >
                          <td className="py-3 px-4 text-sm text-slate-300">{formatDateTime(call.started_at)}</td>
                          <td className="py-3 px-4 text-sm text-slate-300">{formatDateTime(call.ended_at)}</td>
                          <td className="py-3 px-4 text-sm text-slate-300">{formatDuration(call.duration)}</td>
                          <td className="py-3 px-4 text-sm text-white">{call.caller || '-'}</td>
                          <td className="py-3 px-4 text-sm">
                            {call.outcome ? (
                              <span className={`px-2 py-0.5 rounded text-xs font-medium text-white ${getOutcomeColor(call.outcome)}`}>
                                {formatOutcome(call.outcome)}
                              </span>
                            ) : (
                              <span className="text-slate-400">-</span>
                            )}
                          </td>
                          <td className="py-3 px-4 text-center">
                            <AnalyticsStatusIndicator
                              status={call.analytics_status}
                              error={call.analytics_error}
                              t={t}
                            />
                          </td>
                          {/* Cost cell hidden - cost calculation not fully implemented
                          <td className="py-3 px-4 text-sm text-slate-300">
                            {call.cost_total ? `$${call.cost_total.toFixed(4)}` : '-'}
                          </td>
                          */}
                          <td className="py-3 px-4 text-right">
                            <ChevronRight className="w-4 h-4 text-slate-400 inline-block" />
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                </TooltipProvider>
              )}
            </div>
          </Card>
        </div>
      </div>

      <ExportModal
        isOpen={isExportModalOpen}
        onClose={handleCloseExportModal}
        data={callLogs}
        onExport={handleExport}
      />
    </>
  );
}
