import { useContext, useEffect, useState } from "react";
import { AccountContext } from "../../contexts/AccountContext";
import { Account, AccountType } from "../../data";
import * as Yup from 'yup';
import { axiosInstance } from "../../../axiosApi";
import { AxiosResponse } from "axios";
import { ErrorMessage, Field, Form, Formik } from "formik";
import Header2 from "../../components/Header2/Header2";
import ParticleBackground from "../../components/ParticleBackground/ParticleBackground";
import styled from "styled-components";
import ThemeSettingsCard from "../../components/ThemeSettingsCard/ThemeSettingsCard";
import UsageSummaryCard from "../../components/UsageSummaryCard/UsageSummaryCard";
import BillingSection from "../../components/BillingSection/BillingSection";
import DeleteAccountSection from "../../components/DeleteAccountSection/DeleteAccountSection";

// 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;
  /* background-color: ${({ theme }) => theme.colors.background}; Removed to show particles */
`;

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 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 StyledTable = styled.table`
  width: 100%;
  border-collapse: collapse;
  margin-top: 1rem;
`;

const Th = styled.th`
  text-align: left;
  padding: 1rem;
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  color: ${({ theme }) => theme.colors.text};
  opacity: 0.7;
  font-weight: 600;
`;

const Td = styled.td`
  padding: 1rem;
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  color: ${({ theme }) => theme.colors.text};
`;

const StyledInput = styled.input`
  width: 100%;
  background: ${({ theme }) => theme.darkMode ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)'};
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 0.5rem;
  padding: 0.8rem;
  color: ${({ theme }) => theme.colors.text};
  font-size: 1rem;
  outline: none;
  transition: all 0.3s ease;

  &:focus {
    background: ${({ theme }) => theme.darkMode ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'};
    border-color: ${({ theme }) => theme.main};
    box-shadow: 0 0 10px ${({ theme }) => theme.main}33; // 33 is approx 20% opacity
  }
`;

const StyledButton = styled.button`
  background: ${({ theme }) => theme.main};
  border: none;
  border-radius: 0.5rem;
  color: #fff;
  padding: 0.8rem 1.5rem;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  margin-top: 1rem;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px ${({ theme }) => theme.main}66; // 66 is approx 40% opacity
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    transform: none;
  }
`;

const ToggleSwitch = styled.label`
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
`;

const Slider = styled.span`
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: ${({ theme }) => theme.darkMode ? 'rgba(255, 255, 255, 0.2)' : 'rgba(0, 0, 0, 0.2)'};
  transition: .4s;
  border-radius: 24px;

  &:before {
    position: absolute;
    content: "";
    height: 16px;
    width: 16px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
  }
`;

const Checkbox = styled.input`
  opacity: 0;
  width: 0;
  height: 0;

  &:checked + ${Slider} {
    background-color: ${({ theme }) => theme.main};
  }

  &:checked + ${Slider}:before {
    transform: translateX(26px);
  }
  
  &:disabled + ${Slider} {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;

const DeleteButton = styled.button`
  background: transparent;
  border: none;
  color: #ff6b6b;
  cursor: pointer;
  font-size: 1.2rem;
  transition: color 0.2s ease;

  &:hover {
    color: #ff4757;
  }
`;

type InviteValues = {
  email: string
}
const validationSchema = Yup.object().shape({
  email: Yup.string().email().required("This is required")
}
)

type AddUserCardProps = {
  getCompanyUsers: () => void;
}

type CompanyAccountLineProps = {
  user: Account
  handleUserUpdate: (email: string, field: string, value: string) => void
}

const CompanyAccountLine = ({ user, handleUserUpdate }: CompanyAccountLineProps): JSX.Element => {
  const { account } = useContext(AccountContext);

  return (
    <tr>
      <Td>{user.email}</Td>
      <Td>{user.first_name}</Td>
      <Td>{user.last_name}</Td>
      <Td>
        <ToggleSwitch>
          <Checkbox
            type="checkbox"
            checked={user.is_company_manager}
            onChange={(event) => handleUserUpdate(user.email, 'company_manager', String(event.target.checked))}
            disabled={account?.email === user.email}
          />
          <Slider />
        </ToggleSwitch>
      </Td>
      <Td>
        <ToggleSwitch>
          <Checkbox
            type="checkbox"
            checked={user.is_active}
            onChange={(event) => handleUserUpdate(user.email, 'is_active', String(event.target.checked))}
          />
          <Slider />
        </ToggleSwitch>
      </Td>
      <Td>
        <ToggleSwitch>
          <Checkbox
            type="checkbox"
            checked={user.has_password && user.has_signed_tos}
            onChange={(event) => handleUserUpdate(user.email, 'has_password', String(event.target.checked))}
            disabled={!user.has_password}
          />
          <Slider />
        </ToggleSwitch>
      </Td>
      <Td>
        <DeleteButton onClick={() => handleUserUpdate(user.email, 'delete', '')}>
          🗑️
        </DeleteButton>
      </Td>
    </tr>
  )
}

const AddUserCard = ({ getCompanyUsers }: AddUserCardProps): JSX.Element => {
  const initialValues = { 'email': '', }
  const handleInvite = async ({ email }: InviteValues, { resetForm }: any): Promise<void> => {
    try {
      await axiosInstance.post('/user/invite/', {
        'email': email
      })
      getCompanyUsers()

    } catch {
      // put a message here
    }
    resetForm();

  }
  return (
    <GlassCard>
      <CardTitle>Invite A User</CardTitle>
      <Formik
        initialValues={initialValues}
        onSubmit={handleInvite}
        validateOnMount
        validationSchema={validationSchema}>
        {(formik) =>
          <Form>
            <div style={{ display: 'flex', gap: '1rem', alignItems: 'flex-start' }}>
              <div style={{ flex: 1 }}>
                <Field
                  name={"email"}
                  as={StyledInput}
                  placeholder={"Email Address"}
                />
                <ErrorMessage name="email">
                  {msg => <div style={{ color: '#ff6b6b', marginTop: '0.5rem', fontSize: '0.9rem' }}>{msg}</div>}
                </ErrorMessage>
              </div>
              <StyledButton
                type={'submit'}
                disabled={!formik.isValid || formik.isSubmitting}
                style={{ marginTop: 0 }}
              >
                Invite
              </StyledButton>
            </div>
          </Form>
        }
      </Formik>
    </GlassCard>
  )
}

const CompanyManagerCard = (): JSX.Element => {
  const [users, setUsers] = useState<Account[]>([]);

  const handleUserUpdate = async (email: string, field: string, value: string): Promise<void> => {
    //console.log(email, field, value)
    if (field === 'delete') {
      await axiosInstance.delete(`/company_users`, {
        data: { 'email': email }

      })
    } else {
      await axiosInstance.post(`/company_users`, {
        'email': email,
        'field': field,
        'value': value
      });
    }



    // get all of th edata again
    try {
      const { data, }: AxiosResponse<AccountType[]> = await axiosInstance.get(`/company_users`);
      setUsers(data.map((item) => new Account({

        email: item.email,
        first_name: item.first_name,
        last_name: item.last_name,
        is_company_manager: item.is_company_manager,
        has_password: item.has_usable_password,
        is_active: item.is_active,
        company: undefined
      })))


    } catch (error) {
      console.log(error)
    }

  }

  async function getCompanyUsers() {
    try {
      const { data, }: AxiosResponse<AccountType[]> = await axiosInstance.get(`/company_users`);
      setUsers(data.map((item) => new Account({

        email: item.email,
        first_name: item.first_name,
        last_name: item.last_name,
        is_company_manager: item.is_company_manager,
        has_password: item.has_usable_password,
        is_active: item.is_active,
        has_signed_tos: item.has_signed_tos,
        company: undefined
      })))


    } catch (error) {
      console.log(error)
    }
  }

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

  return (
    <>
      <GlassCard>
        <CardTitle>Company Accounts</CardTitle>
        <div style={{ overflowX: 'auto' }}>
          <StyledTable>
            <thead>
              <tr>
                <Th>Email</Th>
                <Th>First Name</Th>
                <Th>Last Name</Th>
                <Th>Is Manager</Th>
                <Th>Is Active</Th>
                <Th>Has Password</Th>
                <Th>Delete</Th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => <CompanyAccountLine user={user} handleUserUpdate={handleUserUpdate} key={user.email} />)}
            </tbody>
          </StyledTable>
        </div>
      </GlassCard>
      <AddUserCard getCompanyUsers={getCompanyUsers} />
    </>

  )
}

const AccountPage = (): JSX.Element => {
  const { account } = useContext(AccountContext)

  return (
    <>
      <ThemeSettingsCard />
      <UsageSummaryCard />
      <BillingSection />
      {account?.is_company_manager ? (
        <CompanyManagerCard />
      ) : (
        <GlassCard>
          <CardTitle>Account Information</CardTitle>
          <p style={{ color: 'rgba(255,255,255,0.7)' }}>Account and prompt information will be available soon</p>
        </GlassCard>
      )}
      <DeleteAccountSection />
    </>
  )
}

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

export default Account2