import React, { useState, useEffect, useCallback } from "react";
import { Card, CardContent } from "@/components/ui/card";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
} from "@/components/ui/select";
import {
  Mail,
  Send,
  ArrowUp,
  ArrowDown,
  Zap,
  Timer,
  BarChart3,
  ClipboardCheck,
  Star,
} from "lucide-react";
import axios from "axios";
import { CARD_STYLES } from "@/lib/dashboard/designTokens";
import {
  DashboardStatCard,
  DashboardStatCardSkeleton,
  DashboardSectionHeader,
  DashboardErrorState,
  DashboardTable,
} from "@/components/dashboard/shared";

const TIME_RANGES = {
  "today": "Today",
  "7": "Last 7 Days",
  "14": "Last 14 Days",
  "30": "Last 30 Days",
  "90": "Last 90 Days",
};

const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
};

const getDateRange = (days) => {
  const now = new Date();
  const easternTime = new Date(
    now.toLocaleString("en-US", { timeZone: "America/New_York" })
  );

  if (days === "today") {
    const start = new Date(easternTime);
    start.setHours(0, 0, 0, 0);

    const end = new Date(easternTime);
    end.setHours(23, 59, 59, 999);

    return {
      start_datetime: start.toISOString(),
      end_datetime: end.toISOString()
    };
  }

  const end = new Date(easternTime);
  end.setHours(23, 59, 59, 999);

  const start = new Date(easternTime);
  start.setDate(start.getDate() - Number(days));
  start.setHours(0, 0, 0, 0);

  return {
    start_datetime: start.toISOString(),
    end_datetime: end.toISOString()
  };
};

// Trend cell component with arrow and color
const TrendCell = ({ delta }) => {
  if (delta === 0) return null;

  const isPositive = delta > 0;
  const colorClass = isPositive
    ? "text-green-600 dark:text-green-500"
    : "text-red-600 dark:text-red-500";

  return (
    <div className={`flex items-center justify-end gap-0.5 ${colorClass}`}>
      {isPositive ? (
        <ArrowUp className="w-3 h-3" />
      ) : (
        <ArrowDown className="w-3 h-3" />
      )}
      <span>{Math.abs(delta)}%</span>
    </div>
  );
};

const GorgiasOverview = () => {
  const [timeRange, setTimeRange] = useState("7");
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const loadStats = useCallback(async () => {
    setLoading(true);
    const filters = getDateRange(timeRange);

    try {
      const [overview, channelStats, agentStats, satisfaction] =
        await Promise.all([
          axios.post('/api/gorgias/stats/overview', filters)
            .then(res => res.data?.data?.data?.data || []),
          axios.post('/api/gorgias/stats/tickets-created-per-channel', filters)
            .then(res => res.data?.data?.data?.data?.lines || []),
          axios.post('/api/gorgias/stats/tickets-closed-per-agent', filters)
            .then(res => res.data?.data?.data?.data?.lines || []),
          axios.post('/api/gorgias/stats/satisfaction-surveys', filters)
            .then(res => res.data?.data?.data?.data || []),
        ]);

      setData({
        overview,
        channels: channelStats,
        agents: agentStats,
        satisfaction,
      });

      setError(null);
    } catch (err) {
      console.error("Error loading stats:", err);
      const errorMessage = err.response?.data?.error || err.message;
      setError(errorMessage);
      if (err.response?.status === 401) {
        setError('Authentication failed. Please check your Gorgias API credentials.');
      }
    } finally {
      setLoading(false);
    }
  }, [timeRange]);

  useEffect(() => {
    loadStats();
    const interval = setInterval(loadStats, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, [loadStats]);

  // Convert overview array to stats format
  const stats = (data.overview || []).reduce((acc, item) => {
    acc[item.name] = {
      value: item.value || 0,
      delta: item.delta || 0,
      type: item.type,
      more_is_better: item.more_is_better
    };
    return acc;
  }, {});

  // Process satisfaction data
  const satisfactionStats = (data.satisfaction || []).reduce((acc, item) => {
    if (item.name !== 'response_distribution') {
      acc[item.name] = {
        value: item.value || 0,
        delta: item.delta || 0,
        type: item.type,
        more_is_better: item.more_is_better
      };
    }
    return acc;
  }, {});

  // Process channel data
  const channels = (data.channels?.map(line => ({
    name: line[0]?.value || '',
    total: line[1]?.value || 0,
    percentage: line[2]?.value || 0,
    delta: line[3]?.value || 0
  })) || []).sort((a, b) => b.total - a.total);

  // Process agent data
  const agents = (data.agents?.map(line => ({
    name: line[0]?.value || '',
    closed: line[1]?.value || 0,
    rating: line[2]?.value,
    percentage: line[3]?.value || 0,
    delta: line[4]?.value || 0
  })) || []).filter(agent => agent.name !== "Unassigned");

  // Column definitions for Channel Distribution table
  const channelColumns = [
    {
      key: "name",
      header: "Channel",
      render: (value) => <span className="text-foreground">{value}</span>,
    },
    {
      key: "total",
      header: "Total",
      align: "right",
      render: (value) => <span className="text-muted-foreground">{value}</span>,
    },
    {
      key: "percentage",
      header: "%",
      align: "right",
      render: (value) => <span className="text-muted-foreground">{value}%</span>,
    },
    {
      key: "delta",
      header: "Change",
      align: "right",
      render: (value) => <TrendCell delta={value} />,
    },
  ];

  // Column definitions for Agent Performance table
  const agentColumns = [
    {
      key: "name",
      header: "Agent",
      render: (value) => <span className="text-foreground">{value}</span>,
    },
    {
      key: "closed",
      header: "Closed",
      align: "right",
      render: (value) => <span className="text-muted-foreground">{value}</span>,
    },
    {
      key: "rating",
      header: "Rating",
      align: "right",
      render: (value) => (
        <span className="text-muted-foreground">
          {value ? `${value}/5` : "-"}
        </span>
      ),
    },
    {
      key: "delta",
      header: "Change",
      align: "right",
      render: (value) => <TrendCell delta={value} />,
    },
  ];

  if (error) {
    return (
      <Card className={`h-full ${CARD_STYLES.base}`}>
        <CardContent className="p-4">
          <DashboardErrorState
            title="Failed to load customer service data"
            error={error}
          />
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className={`h-full ${CARD_STYLES.base}`}>
      <DashboardSectionHeader
        title="Customer Service"
        timeSelector={
          <Select
            value={timeRange}
            onValueChange={(value) => setTimeRange(value)}
          >
            <SelectTrigger className="w-[130px] bg-background">
              <SelectValue placeholder="Select range">
                {TIME_RANGES[timeRange]}
              </SelectValue>
            </SelectTrigger>
            <SelectContent>
              {[
                ["today", "Today"],
                ["7", "Last 7 Days"],
                ["14", "Last 14 Days"],
                ["30", "Last 30 Days"],
                ["90", "Last 90 Days"],
              ].map(([value, label]) => (
                <SelectItem key={value} value={value}>
                  {label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        }
      />

      <CardContent className="space-y-4">
        <div className="grid grid-cols-2 sm:grid-cols-4 2xl:grid-cols-7 gap-4 dashboard-stagger">
          {loading ? (
            [...Array(7)].map((_, i) => (
              <DashboardStatCardSkeleton key={i} />
            ))
          ) : (
            <>
              <DashboardStatCard
                title="Messages Received"
                value={stats.total_messages_received?.value ?? 0}
                trend={stats.total_messages_received?.delta ? {
                  value: stats.total_messages_received.delta,
                  suffix: "",
                } : undefined}
  
              />
              <DashboardStatCard
                title="Messages Sent"
                value={stats.total_messages_sent?.value ?? 0}
                trend={stats.total_messages_sent?.delta ? {
                  value: stats.total_messages_sent.delta,
                  suffix: "",
                } : undefined}

              />
              <DashboardStatCard
                title="First Response"
                value={formatDuration(stats.median_first_response_time?.value)}
                trend={stats.median_first_response_time?.delta ? {
                  value: stats.median_first_response_time.delta,
                  suffix: "",
                  moreIsBetter: false,
                } : undefined}

              />
              <DashboardStatCard
                title="One-Touch Rate"
                value={stats.total_one_touch_tickets?.value ?? 0}
                valueSuffix="%"
                trend={stats.total_one_touch_tickets?.delta ? {
                  value: stats.total_one_touch_tickets.delta,
                  suffix: "%",
                } : undefined}
 
              />
              <DashboardStatCard
                title="Customer Satisfaction"
                value={`${satisfactionStats.average_rating?.value ?? 0}/5`}
                trend={satisfactionStats.average_rating?.delta ? {
                  value: satisfactionStats.average_rating.delta,
                  suffix: "%",
                } : undefined}
 
              />
              <DashboardStatCard
                title="Survey Response Rate"
                value={satisfactionStats.response_rate?.value ?? 0}
                valueSuffix="%"
                trend={satisfactionStats.response_rate?.delta ? {
                  value: satisfactionStats.response_rate.delta,
                  suffix: "%",
                } : undefined}

              />
              <DashboardStatCard
                title="Resolution Time"
                value={formatDuration(stats.median_resolution_time?.value)}
                trend={stats.median_resolution_time?.delta ? {
                  value: stats.median_resolution_time.delta,
                  suffix: "",
                  moreIsBetter: false,
                } : undefined}

              />
            </>
          )}
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Channel Distribution */}
          <Card className={CARD_STYLES.base}>
            <DashboardSectionHeader title="Channel Distribution" compact className="pb-0" />
            <CardContent>
              <DashboardTable
                columns={channelColumns}
                data={channels}
                loading={loading}
                skeletonRows={5}
                getRowKey={(channel, index) => `${channel.name}-${index}`}
                maxHeight="md"
                compact
              />
            </CardContent>
          </Card>

          {/* Agent Performance */}
          <Card className={CARD_STYLES.base}>
            <DashboardSectionHeader title="Agent Performance" compact className="pb-0" />
            <CardContent>
              <DashboardTable
                columns={agentColumns}
                data={agents}
                loading={loading}
                skeletonRows={5}
                getRowKey={(agent, index) => `${agent.name}-${index}`}
                maxHeight="md"
                compact
              />
            </CardContent>
          </Card>
        </div>
      </CardContent>
    </Card>
  );
};

export default GorgiasOverview;
