import { useEffect, useState } from "react";
import { Document, DocumentType } from "../../data";
import { AxiosResponse } from "axios";
import { axiosInstance } from "../../../axiosApi";
import Header2 from "../../components/Header2/Header2";
import ParticleBackground from "../../components/ParticleBackground/ParticleBackground";
import styled from "styled-components";

// 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 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;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;

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

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

const FileInputLabel = styled.label`
  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;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  margin-right: 1rem;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px ${({ theme }) => theme.main}66;
  }
`;

const StatusIcon = styled.span<{ status: 'success' | 'pending' }>`
  color: ${props => props.status === 'success' ? '#4caf50' : '#bdbdbd'};
  font-size: 1.5rem;
`;

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;
  }
`;


type DocumentTableCardProps = {
  documents: Document[],
  setDocuments: React.Dispatch<React.SetStateAction<Document[]>>
}

const CompanyDocumentStorageTableCard = ({ documents, setDocuments }: DocumentTableCardProps): JSX.Element => {

  useEffect(() => {
    async function getUploadedDocuments() {
      try {
        const { data, }: AxiosResponse<DocumentType[]> = await axiosInstance.get(`/documents/`);
        setDocuments(data.map((item) => new Document({

          id: item.id,
          name: item.file.replace(/^.*[\\/]/, ''),
          date_uploaded: item.created.substring(0, 10),
          active: item.active,
          processed: item.processed,

        })))


      } catch (error) {
        console.log(error)
      }
    }
    getUploadedDocuments();
  }, [setDocuments])
  return (
    <GlassCard>
      <CardTitle>Your documents in the company workspace</CardTitle>
      <div style={{ overflowX: 'auto' }}>
        <StyledTable>
          <thead>
            <tr>
              <Th>Name</Th>
              <Th>Date Uploaded</Th>
              <Th>Processed</Th>
              <Th>Active</Th>
            </tr>
          </thead>
          <tbody>
            {documents.map((doc) => (
              <tr key={doc.id}>
                <Td>{doc.name}</Td>
                <Td>{doc.date_uploaded}</Td>
                <Td>
                  {doc.processed ? (
                    <StatusIcon status="success">✓</StatusIcon>
                  ) : (
                    <StatusIcon status="pending">⏳</StatusIcon>
                  )}
                </Td>
                <Td>
                  <ToggleSwitch>
                    <Checkbox
                      type="checkbox"
                      checked={doc.active}
                      disabled={true}
                    />
                    <Slider />
                  </ToggleSwitch>
                </Td>
              </tr>
            ))}
          </tbody>
        </StyledTable>
      </div>
    </GlassCard>
  )
}

const UserDocumentStorageTableCard = (): JSX.Element => {
  return (
    <GlassCard>
      <CardTitle>Your documents in your personal workspace</CardTitle>
      <p style={{ color: 'rgba(255,255,255,0.7)' }}>This will become available shortly</p>
    </GlassCard>
  )
}

const DocumentUploadCard = (): JSX.Element => {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

  const handleDocumentUpload = async (): Promise<void> => {

    console.log(selectedFile)
    if (selectedFile) {
      try {
        await axiosInstance.post('/documents/', {
          file: selectedFile
        },
          {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
          })

        // TODO set the documents here
      }
      finally {

      }
    }
  }

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      setSelectedFile(event.target.files[0]);
    }
  };
  return (
    <GlassCard>
      <CardTitle>Upload a Document</CardTitle>
      <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '1rem' }}>
        <FileInputLabel>
          Select File
          <input type="file" hidden onChange={handleFileChange} />
        </FileInputLabel>

        {selectedFile && (
          <>
            <span style={{ color: '#fff' }}>{selectedFile.name}</span>
            <StyledButton onClick={handleDocumentUpload}>
              Upload
            </StyledButton>
          </>
        )}
      </div>
    </GlassCard>
  )
}

const DocumentStoragePageInner = (): JSX.Element => {
  const [documents, setDocuments] = useState<Document[]>([]);
  return (
    <>
      <CompanyDocumentStorageTableCard documents={documents} setDocuments={setDocuments} />
      <UserDocumentStorageTableCard />
      <DocumentUploadCard />
    </>
  )
}

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

export default DocumentStoragePage;