import { useContext, useEffect, useState } from "react"
import Header2 from "../../components/Header2/Header2"
import { AccountContext } from "../../contexts/AccountContext"
import { Area, Bar, BarChart, ComposedChart, Legend, Line, ResponsiveContainer, Tooltip, XAxis, YAxis, Rectangle } from "recharts"
import { axiosInstance } from "../../../axiosApi"
import { AxiosResponse } from "axios"
import { AdminAnalytics, AdminAnalyticsType, CompanyUsageAnalytics, CompanyUsageAnalyticsType, UserConversationAnalytics, UserConvesationAnalyticsType, UserPromptAnalytics, UserPromptAnalyticsType } from "../../data"
import ParticleBackground from "../../components/ParticleBackground/ParticleBackground"
import PromptHeatmapCard from "../../components/PromptHeatmapCard/PromptHeatmapCard"
import styled, { ThemeContext } from "styled-components"

const PageContainer = styled.div`
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  color: ${({ theme }) => theme.colors.text};
  font-family: 'Inter', sans-serif;
`;

const ContentWrapper = styled.div`
  flex: 1;
  overflow-y: auto;
  padding: 6rem 2rem 2rem 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 5;

  &::-webkit-scrollbar {
    width: 8px;
  }
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 4px;
  }
`;

const Section = styled.section`
  width: 100%;
  max-width: 1200px;
  margin-bottom: 1rem;
`;

const SectionHeading = styled.h1`
  width: 100%;
  font-size: 1.35rem;
  font-weight: 700;
  color: ${({ theme }) => theme.colors.text};
  margin: 0 0 1rem 0;
  letter-spacing: 0.02em;
`;

const SectionHint = styled.p`
  margin: -0.5rem 0 1.25rem 0;
  color: ${({ theme }) => theme.colors.text};
  opacity: 0.65;
  font-size: 0.95rem;
  line-height: 1.5;
`;

const GlassCard = styled.div`
  background: ${({ theme }) => theme.colors.cardBackground};
  backdrop-filter: blur(10px);
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 1rem;
  padding: 2rem;
  width: 100%;
  max-width: 1000px;
  margin-bottom: 2rem;
  box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
`;

const CardTitle = styled.h2`
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  color: ${({ theme }) => theme.colors.text};
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  padding-bottom: 1rem;
`;

const GridContainer = styled.div`
  display: grid;
  grid-template-columns: 1fr;
  gap: 2rem;
  width: 100%;
  max-width: 1200px;

  @media (min-width: 992px) {
    grid-template-columns: 1fr 1fr;
  }
`;

const ChartContainer = styled.div`
  width: 100%;
  height: 400px;
`;

const UserPromptAnalyticsCard = (): JSX.Element => {
    const [data, setData] = useState<UserPromptAnalytics[]>([])
    const theme = useContext(ThemeContext);

    async function getUserPromptAnalytics() {
        try {
            const { data, }: AxiosResponse<UserPromptAnalyticsType[]> = await axiosInstance.get(`/analytics/user_prompts/`);
            setData(data)
        } catch (error) {

        }
    }
    useEffect(() => {
        getUserPromptAnalytics();
    }, [])
    return (
        <GlassCard>
            <CardTitle>Prompt volume</CardTitle>
            <ChartContainer>
                <ResponsiveContainer>
                    <BarChart data={data}>
                        <XAxis dataKey="month" stroke={theme?.colors.text} />
                        <YAxis stroke={theme?.colors.text} />
                        <Legend wrapperStyle={{ color: theme?.colors.text }} />
                        <Tooltip contentStyle={{ backgroundColor: theme?.colors.cardBackground, border: `1px solid ${theme?.colors.cardBorder}`, color: theme?.colors.text }} />
                        <Bar dataKey="you" fill={theme?.main || "#667eea"} activeBar={<Rectangle fill={theme?.main ? theme.main + "99" : "#764ba2"} stroke={theme?.colors.text} />} />
                        <Bar dataKey="others" fill="#82ca9d" activeBar={<Rectangle fill="#a8e6cf" stroke={theme?.colors.text} />} />
                        <Bar dataKey="all" fill="#ffb7b2" activeBar={<Rectangle fill="#ffdac1" stroke={theme?.colors.text} />} />
                    </BarChart>
                </ResponsiveContainer>
            </ChartContainer>
        </GlassCard>
    )
}

const UserConversationAnalyticsCard = (): JSX.Element => {
    const [data, setData] = useState<UserConversationAnalytics[]>([])
    const theme = useContext(ThemeContext);

    async function getUserConversationAnalytics() {
        try {
            const { data, }: AxiosResponse<UserConvesationAnalyticsType[]> = await axiosInstance.get(`/analytics/user_conversations/`);
            setData(data)
        } catch (error) {

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

    return (
        <GlassCard>
            <CardTitle>Conversation volume</CardTitle>
            <ChartContainer>
                <ResponsiveContainer>
                    <BarChart data={data}>
                        <XAxis dataKey="month" stroke={theme?.colors.text} />
                        <YAxis stroke={theme?.colors.text} />
                        <Legend wrapperStyle={{ color: theme?.colors.text }} />
                        <Tooltip contentStyle={{ backgroundColor: theme?.colors.cardBackground, border: `1px solid ${theme?.colors.cardBorder}`, color: theme?.colors.text }} />
                        <Bar dataKey="you" fill={theme?.main || "#667eea"} activeBar={<Rectangle fill={theme?.main ? theme.main + "99" : "#764ba2"} stroke={theme?.colors.text} />} />
                        <Bar dataKey="others" fill="#82ca9d" activeBar={<Rectangle fill="#a8e6cf" stroke={theme?.colors.text} />} />
                        <Bar dataKey="all" fill="#ffb7b2" activeBar={<Rectangle fill="#ffdac1" stroke={theme?.colors.text} />} />
                    </BarChart>
                </ResponsiveContainer>
            </ChartContainer>
        </GlassCard>
    )
}

const CompanyUsageAnalyticsCard = (): JSX.Element => {
    const [data, setData] = useState<CompanyUsageAnalytics[]>([])
    const theme = useContext(ThemeContext);

    async function getCompanyUsageAnalytics() {
        try {
            const { data, }: AxiosResponse<CompanyUsageAnalyticsType[]> = await axiosInstance.get(`/analytics/company_usage/`);
            setData(data)
        } catch (error) {

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

    return (
        <GlassCard>
            <CardTitle>Team seat activity</CardTitle>
            <ChartContainer>
                <ResponsiveContainer>
                    <BarChart data={data}>
                        <XAxis dataKey="month" stroke={theme?.colors.text} />
                        <YAxis stroke={theme?.colors.text} />
                        <Legend wrapperStyle={{ color: theme?.colors.text }} />
                        <Tooltip contentStyle={{ backgroundColor: theme?.colors.cardBackground, border: `1px solid ${theme?.colors.cardBorder}`, color: theme?.colors.text }} />
                        <Bar dataKey="used" fill={theme?.main || "#667eea"} activeBar={<Rectangle fill={theme?.main ? theme.main + "99" : "#764ba2"} stroke={theme?.colors.text} />} />
                        <Bar dataKey="not_used" fill="#82ca9d" activeBar={<Rectangle fill="#a8e6cf" stroke={theme?.colors.text} />} />
                    </BarChart>
                </ResponsiveContainer>
            </ChartContainer>
        </GlassCard>
    )
}

const AdminAnalyticsCard = (): JSX.Element => {
    const [data, setData] = useState<AdminAnalytics[]>([])
    const theme = useContext(ThemeContext);

    async function getAdminAnalytics() {
        try {
            const { data, }: AxiosResponse<AdminAnalyticsType[]> = await axiosInstance.get(`/analytics/admin/`);
            setData(data)
        } catch (error) {

        }
    }
    useEffect(() => {
        getAdminAnalytics();
    }, [])
    return (
        <GlassCard>
            <CardTitle>Response times (ops)</CardTitle>
            <ChartContainer>
                <ResponsiveContainer>
                    <ComposedChart data={data}>
                        <XAxis dataKey="month" stroke={theme?.colors.text} />
                        <YAxis stroke={theme?.colors.text} />
                        <Legend wrapperStyle={{ color: theme?.colors.text }} />
                        <Tooltip contentStyle={{ backgroundColor: theme?.colors.cardBackground, border: `1px solid ${theme?.colors.cardBorder}`, color: theme?.colors.text }} />
                        <Area
                            dataKey="range"
                            dot={false}
                            connectNulls
                            activeDot={false}
                            fill="#8884d8"
                            stroke="#8884d8"
                        />
                        <Line type="natural" dataKey="avg" connectNulls stroke="#ff7300" />
                        <Line type="monotone" dataKey="median" connectNulls stroke="#387908" />
                    </ComposedChart>
                </ResponsiveContainer>
            </ChartContainer>
        </GlassCard>
    )
}

const isOpsAdmin = (email?: string, role?: string): boolean => {
    if (role && ['admin', 'ops', 'staff'].includes(role.toLowerCase())) {
        return true;
    }
    return email === "ryan+admin@aimloperations.com";
};

const AnalyticsInner = (): JSX.Element => {
    const { account } = useContext(AccountContext)
    const showCompany = Boolean(account?.is_company_manager || account?.company);
    const showAdmin = isOpsAdmin(account?.email, account?.role);

    return (
        <>
            <Section aria-labelledby="analytics-you">
                <SectionHeading id="analytics-you">Your activity</SectionHeading>
                <SectionHint>
                    Personal prompt timing and volume. Other users&apos; private messages are never shown here.
                </SectionHint>
                <PromptHeatmapCard />
                <GridContainer>
                    <UserConversationAnalyticsCard />
                    <UserPromptAnalyticsCard />
                </GridContainer>
            </Section>

            {showCompany && (
                <Section aria-labelledby="analytics-company">
                    <SectionHeading id="analytics-company">Company</SectionHeading>
                    <SectionHint>
                        Aggregated seat and usage trends for your workspace. No message content.
                    </SectionHint>
                    {account?.is_company_manager ? (
                        <CompanyUsageAnalyticsCard />
                    ) : (
                        <GlassCard>
                            <CardTitle>Company insights</CardTitle>
                            <p style={{ opacity: 0.7, margin: 0 }}>
                                Detailed team seat charts are available to company managers.
                            </p>
                        </GlassCard>
                    )}
                </Section>
            )}

            {showAdmin && (
                <Section aria-labelledby="analytics-ops">
                    <SectionHeading id="analytics-ops">Operations</SectionHeading>
                    <AdminAnalyticsCard />
                </Section>
            )}
        </>
    )
}

const AnalyticsPage = (): JSX.Element => {
    return (
        <PageContainer>
            <ParticleBackground />
            <Header2 />
            <ContentWrapper>
                <AnalyticsInner />
            </ContentWrapper>
        </PageContainer>
    )
}

export default AnalyticsPage;
