import React, { useState, useEffect, useCallback } from "react";
import { Card, CardContent, CardHeader } from "@/components/dashboard/ui/card";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
} from "@/components/dashboard/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/dashboard/ui/table";
import { Skeleton } from "@/components/dashboard/ui/skeleton";
import {
  Clock,
  Star,
  MessageSquare,
  Mail,
  Send,
  Loader2,
  ArrowUp,
  ArrowDown,
  Zap,
  Timer,
  BarChart3,
  ClipboardCheck,
} from "lucide-react";
import axios from "axios";

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) => {
  // Create date in Eastern Time
  const now = new Date();
  const easternTime = new Date(
    now.toLocaleString("en-US", { timeZone: "America/New_York" })
  );
  
  if (days === "today") {
    // For today, set the range to be the current day in Eastern Time
    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()
    };
  }
  
  // For other periods, calculate from end of previous day
  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()
  };
};

const MetricCard = ({
  title,
  value,
  delta,
  suffix = "",
  icon: Icon,
  colorClass = "blue",
  more_is_better = true,
  loading = false,
}) => {
  const getDeltaColor = (d) => {
    if (d === 0) return "text-gray-600 dark:text-gray-400";
    const isPositive = d > 0;
    return isPositive === more_is_better
      ? "text-green-600 dark:text-green-500"
      : "text-red-600 dark:text-red-500";
  };

  const formatDelta = (d) => {
    if (d === undefined || d === null) return null;
    if (d === 0) return "0";
    return Math.abs(d) + suffix;
  };

  return (
    <Card className="h-full">
      <CardContent className="pt-6 h-full">
        <div className="flex justify-between items-start">
          <div className="flex-1 min-w-0">
            {loading ? (
              <>
                <Skeleton className="h-4 w-24 mb-4 dark:bg-gray-700" />
                <div className="flex items-baseline gap-2">
                  <Skeleton className="h-8 w-20 dark:bg-gray-700" />
                  <Skeleton className="h-4 w-12 dark:bg-gray-700" />
                </div>
              </>
            ) : (
              <>
                <p className="text-sm font-medium text-muted-foreground">{title}</p>
                <div className="flex items-baseline gap-2">
                  <p className="text-2xl font-bold">
                    {typeof value === "number"
                      ? value.toLocaleString() + suffix
                      : value}
                  </p>
                  {delta !== undefined && delta !== 0 && (
                    <div className={`flex items-center ${getDeltaColor(delta)}`}>
                      {delta > 0 ? (
                        <ArrowUp className="w-3 h-3" />
                      ) : (
                        <ArrowDown className="w-3 h-3" />
                      )}
                      <span className="text-xs font-medium">
                        {formatDelta(delta)}
                      </span>
                    </div>
                  )}
                </div>
              </>
            )}
          </div>
          {!loading && Icon && (
            <Icon className={`h-5 w-5 flex-shrink-0 ml-2 ${colorClass === "blue" ? "text-blue-500" : 
              colorClass === "green" ? "text-green-500" :
              colorClass === "purple" ? "text-purple-500" :
              colorClass === "indigo" ? "text-indigo-500" :
              colorClass === "orange" ? "text-orange-500" :
              colorClass === "teal" ? "text-teal-500" :
              colorClass === "cyan" ? "text-cyan-500" :
              "text-blue-500"}`} />
          )}
          {loading && (
            <Skeleton className="h-5 w-5 rounded-full dark:bg-gray-700" />
          )}
        </div>
      </CardContent>
    </Card>
  );
};

const SkeletonMetricCard = () => (
  <Card className="h-full">
    <CardContent className="pt-6 h-full">
      <div className="flex justify-between items-start">
        <div className="flex-1 min-w-0">
          <Skeleton className="h-4 w-24 mb-4 bg-muted" />
          <div className="flex items-baseline gap-2">
            <Skeleton className="h-8 w-20 bg-muted" />
            <Skeleton className="h-4 w-12 bg-muted" />
          </div>
        </div>
        <Skeleton className="h-5 w-5 rounded-full bg-muted" />
      </div>
    </CardContent>
  </Card>
);

const TableSkeleton = () => (
  <Table>
    <TableHeader>
      <TableRow className="dark:border-gray-800">
        <TableHead><Skeleton className="h-4 w-24 bg-muted" /></TableHead>
        <TableHead className="text-right"><Skeleton className="h-4 w-16 ml-auto bg-muted" /></TableHead>
        <TableHead className="text-right"><Skeleton className="h-4 w-16 ml-auto bg-muted" /></TableHead>
        <TableHead className="text-right"><Skeleton className="h-4 w-16 ml-auto bg-muted" /></TableHead>
      </TableRow>
    </TableHeader>
    <TableBody>
      {[...Array(5)].map((_, i) => (
        <TableRow key={i} className="dark:border-gray-800">
          <TableCell><Skeleton className="h-4 w-32 bg-muted" /></TableCell>
          <TableCell className="text-right"><Skeleton className="h-4 w-12 ml-auto bg-muted" /></TableCell>
          <TableCell className="text-right"><Skeleton className="h-4 w-12 ml-auto bg-muted" /></TableCell>
          <TableCell className="text-right"><Skeleton className="h-4 w-16 ml-auto bg-muted" /></TableCell>
        </TableRow>
      ))}
    </TableBody>
  </Table>
);

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 || []),
        ]);

      console.log('Raw API responses:', {
        overview,
        channelStats,
        agentStats,
        satisfaction,
      });

      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();
    // Set up auto-refresh every 5 minutes
    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;
  }, {});

  console.log('Processed stats:', stats);

  // 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;
  }, {});

  console.log('Processed satisfaction stats:', satisfactionStats);

  // 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
  })) || [];

  console.log('Processed channels:', channels);

  // 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
  })) || [];

  console.log('Processed agents:', agents);

  if (error) {
    return (
      <Card className="h-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
        <CardContent className="p-4">
          <div className="p-4 m-6 text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/10 rounded-lg border border-red-200 dark:border-red-900/20">
            {error}
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="h-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
      <CardHeader>
        <div className="flex justify-between items-center">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
            Customer Service
          </h2>
          <div className="flex items-center gap-2">
            <Select
              value={timeRange}
              onValueChange={(value) => setTimeRange(value)}
            >
              <SelectTrigger className="w-[130px] bg-white dark:bg-gray-800">
                <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>
          </div>
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {/* Message & Response Metrics */}
          {loading ? (
            [...Array(7)].map((_, i) => (
              <SkeletonMetricCard key={i} />
            ))
          ) : (
            <>
              <div className="h-full">
                <MetricCard
                  title="Messages Received"
                  value={stats.total_messages_received?.value}
                  delta={stats.total_messages_received?.delta}
                  icon={Mail}
                  colorClass="blue"
                  loading={loading}
                />
              </div>
              <div className="h-full">
                <MetricCard
                  title="Messages Sent"
                  value={stats.total_messages_sent?.value}
                  delta={stats.total_messages_sent?.delta}
                  icon={Send}
                  colorClass="green"
                  loading={loading}
                />
              </div>
              <div className="h-full">
                <MetricCard
                  title="First Response"
                  value={formatDuration(stats.median_first_response_time?.value)}
                  delta={stats.median_first_response_time?.delta}
                  icon={Zap}
                  colorClass="purple"
                  more_is_better={false}
                  loading={loading}
                />
              </div>
              <div className="h-full">
                <MetricCard
                  title="One-Touch Rate"
                  value={stats.total_one_touch_tickets?.value}
                  delta={stats.total_one_touch_tickets?.delta}
                  suffix="%"
                  icon={BarChart3}
                  colorClass="indigo"
                  loading={loading}
                />
              </div>
              <div className="h-full">
                <MetricCard
                  title="Customer Satisfaction"
                  value={`${satisfactionStats.average_rating?.value}/5`}
                  delta={satisfactionStats.average_rating?.delta}
                  suffix="%"
                  icon={Star}
                  colorClass="orange"
                  loading={loading}
                />
              </div>
              <div className="h-full">
                <MetricCard
                  title="Survey Response Rate"
                  value={satisfactionStats.response_rate?.value}
                  delta={satisfactionStats.response_rate?.delta}
                  suffix="%"
                  icon={ClipboardCheck}
                  colorClass="pink"
                  loading={loading}
                />
              </div>
              <div className="h-full">
                <MetricCard
                  title="Resolution Time"
                  value={formatDuration(stats.median_resolution_time?.value)}
                  delta={stats.median_resolution_time?.delta}
                  icon={Timer}
                  colorClass="teal"
                  more_is_better={false}
                  loading={loading}
                />
              </div>
            </>
          )}
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Channel Distribution */}
          <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
            <CardHeader className="pb-0">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                Channel Distribution
              </h3>
            </CardHeader>
            <CardContent className="overflow-y-auto max-h-[400px] scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-gray-700 scrollbar-track-transparent hover:scrollbar-thumb-gray-300 dark:hover:scrollbar-thumb-gray-600">
              {loading ? (
                <TableSkeleton />
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow className="dark:border-gray-800">
                      <TableHead className="text-left font-medium text-gray-900 dark:text-gray-100">Channel</TableHead>
                      <TableHead className="text-right font-medium text-gray-900 dark:text-gray-100">Total</TableHead>
                      <TableHead className="text-right font-medium text-gray-900 dark:text-gray-100">%</TableHead>
                      <TableHead className="text-right font-medium text-gray-900 dark:text-gray-100">Change</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {channels
                      .sort((a, b) => b.total - a.total)
                      .map((channel, index) => (
                        <TableRow key={index} className="dark:border-gray-800 hover:bg-muted/50 transition-colors">
                          <TableCell className="text-gray-900 dark:text-gray-100">
                            {channel.name}
                          </TableCell>
                          <TableCell className="text-right text-muted-foreground">
                            {channel.total}
                          </TableCell>
                          <TableCell className="text-right text-muted-foreground">
                            {channel.percentage}%
                          </TableCell>
                          <TableCell
                            className={`text-right ${
                              channel.delta > 0
                                ? "text-green-600 dark:text-green-500"
                                : channel.delta < 0
                                ? "text-red-600 dark:text-red-500"
                                : "text-muted-foreground"
                            }`}
                          >
                            <div className="flex items-center justify-end gap-0.5">
                              {channel.delta !== 0 && (
                                <>
                                  {channel.delta > 0 ? (
                                    <ArrowUp className="w-3 h-3" />
                                  ) : (
                                    <ArrowDown className="w-3 h-3" />
                                  )}
                                  <span>{Math.abs(channel.delta)}%</span>
                                </>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>

          {/* Agent Performance */}
          <Card className="bg-white dark:bg-gray-900/60 backdrop-blur-sm">
            <CardHeader className="pb-0">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                Agent Performance
              </h3>
            </CardHeader>
            <CardContent className="overflow-y-auto max-h-[400px] scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-gray-700 scrollbar-track-transparent hover:scrollbar-thumb-gray-300 dark:hover:scrollbar-thumb-gray-600">
              {loading ? (
                <TableSkeleton />
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow className="dark:border-gray-800">
                      <TableHead className="text-left font-medium text-gray-900 dark:text-gray-100">Agent</TableHead>
                      <TableHead className="text-right font-medium text-gray-900 dark:text-gray-100">Closed</TableHead>
                      <TableHead className="text-right font-medium text-gray-900 dark:text-gray-100">Rating</TableHead>
                      <TableHead className="text-right font-medium text-gray-900 dark:text-gray-100">Change</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {agents
                      .filter((agent) => agent.name !== "Unassigned")
                      .map((agent, index) => (
                        <TableRow key={index} className="dark:border-gray-800 hover:bg-muted/50 transition-colors">
                          <TableCell className="text-gray-900 dark:text-gray-100">
                            {agent.name}
                          </TableCell>
                          <TableCell className="text-right text-muted-foreground">
                            {agent.closed}
                          </TableCell>
                          <TableCell className="text-right text-muted-foreground">
                            {agent.rating ? `${agent.rating}/5` : "-"}
                          </TableCell>
                          <TableCell
                            className={`text-right ${
                              agent.delta > 0
                                ? "text-green-600 dark:text-green-500"
                                : agent.delta < 0
                                ? "text-red-600 dark:text-red-500"
                                : "text-muted-foreground"
                            }`}
                          >
                            <div className="flex items-center justify-end gap-0.5">
                              {agent.delta !== 0 && (
                                <>
                                  {agent.delta > 0 ? (
                                    <ArrowUp className="w-3 h-3" />
                                  ) : (
                                    <ArrowDown className="w-3 h-3" />
                                  )}
                                  <span>{Math.abs(agent.delta)}%</span>
                                </>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </div>
      </CardContent>
    </Card>
  );
};

export default GorgiasOverview; 