import { FileRecord, RecognitionResult } from '../types';

// Mock Data Store
class MockStore {
  private files: FileRecord[] = [];
  private results: Record<string, RecognitionResult> = {};
  private currentUser = { id: 'mock-user-id', email: 'demo@texpixel.ai' };

  constructor() {
    // Add some initial mock data
    this.addInitialData();
  }

  private addInitialData() {
    const fileId = 'mock-file-1';
    const file: FileRecord = {
      id: fileId,
      user_id: this.currentUser.id,
      filename: 'math-formula-example.jpg',
      file_path: 'https://images.pexels.com/photos/3729557/pexels-photo-3729557.jpeg?auto=compress&cs=tinysrgb&w=800',
      file_type: 'image/jpeg',
      file_size: 1024 * 500, // 500KB
      thumbnail_path: null,
      status: 'completed',
      created_at: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // 1 day ago
      updated_at: new Date().toISOString(),
    };

    const result: RecognitionResult = {
      id: 'mock-result-1',
      file_id: fileId,
      markdown_content: `# Quadratic Formula

The quadratic formula is a fundamental equation in algebra.

$$x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$$

Where:
- $a$, $b$, and $c$ are coefficients
- $x$ represents the solutions

## Example

For the equation $2x^2 + 5x - 3 = 0$:

$$x = \\frac{-5 \\pm \\sqrt{25 - 4(2)(-3)}}{4} = \\frac{-5 \\pm \\sqrt{49}}{4} = \\frac{-5 \\pm 7}{4}$$

Solutions: $x_1 = 0.5$, $x_2 = -3$`,
      latex_content: `\\documentclass{article}
\\begin{document}

\\section*{Quadratic Formula}

The quadratic formula is a fundamental equation in algebra.

\\[
x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}
\\]

Where:
\\begin{itemize}
    \\item $a$, $b$, and $c$ are coefficients
    \\item $x$ represents the solutions
\\end{itemize}

\\end{document}`,
      mathml_content: `<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
  <mrow>
    <mi>x</mi>
    <mo>=</mo>
    <mfrac>
      <mrow>
        <mo>-</mo>
        <mi>b</mi>
        <mo>±</mo>
        <msqrt>
          <mrow>
            <msup>
              <mi>b</mi>
              <mn>2</mn>
            </msup>
            <mo>-</mo>
            <mn>4</mn>
            <mi>a</mi>
            <mi>c</mi>
          </mrow>
        </msqrt>
      </mrow>
      <mrow>
        <mn>2</mn>
        <mi>a</mi>
      </mrow>
    </mfrac>
  </mrow>
</math>`,
      mml: `<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML" display="block">
  <mml:mrow>
    <mml:mi>x</mml:mi>
    <mml:mo>=</mml:mo>
    <mml:mfrac>
      <mml:mrow>
        <mml:mo>-</mml:mo>
        <mml:mi>b</mml:mi>
        <mml:mo>±</mml:mo>
        <mml:msqrt>
          <mml:mrow>
            <mml:msup>
              <mml:mi>b</mml:mi>
              <mml:mn>2</mml:mn>
            </mml:msup>
            <mml:mo>-</mml:mo>
            <mml:mn>4</mml:mn>
            <mml:mi>a</mml:mi>
            <mml:mi>c</mml:mi>
          </mml:mrow>
        </mml:msqrt>
      </mml:mrow>
      <mml:mrow>
        <mml:mn>2</mml:mn>
        <mml:mi>a</mml:mi>
      </mml:mrow>
    </mml:mfrac>
  </mml:mrow>
</mml:math>`,
      rendered_image_path: 'https://images.pexels.com/photos/3729557/pexels-photo-3729557.jpeg?auto=compress&cs=tinysrgb&w=800',
      created_at: new Date().toISOString(),
    };

    this.files.push(file);
    this.results[fileId] = result;
  }

  // File Operations
  async getFiles(userId?: string | null): Promise<FileRecord[]> {
    await this.delay(500); // Simulate network latency
    if (userId) {
      return this.files.filter(f => f.user_id === userId);
    }
    return this.files.filter(f => f.user_id === null); // Anonymous files
  }

  async uploadFile(file: File, userId?: string | null): Promise<FileRecord> {
    await this.delay(1000); // Simulate upload time

    const newFile: FileRecord = {
      id: crypto.randomUUID(),
      user_id: userId || null,
      filename: file.name,
      file_path: URL.createObjectURL(file), // Local blob URL
      file_type: file.type,
      file_size: file.size,
      thumbnail_path: null,
      status: 'completed',
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    };

    this.files.unshift(newFile); // Add to beginning
    this.generateMockResult(newFile.id, file.name);

    return newFile;
  }

  // Method to add a file record manually (e.g. after real upload)
  addFileRecord(fileRecord: FileRecord) {
    this.files.unshift(fileRecord);
    // Don't generate mock result - real API result will be set after polling completes
  }

  // Result Operations
  async getResult(fileId: string): Promise<RecognitionResult | null> {
    await this.delay(300);
    return this.results[fileId] || null;
  }

  private generateMockResult(fileId: string, filename: string) {
    const mockResult: RecognitionResult = {
      id: crypto.randomUUID(),
      file_id: fileId,
      markdown_content: `# Analysis for ${filename}\n\nThis is a mock analysis result generated for the uploaded file.\n\n$$ E = mc^2 $$\n\nDetected content matches widely known physics formulas.`,
      latex_content: `\\documentclass{article}\n\\begin{document}\nSection{${filename}}\n\n\\[ E = mc^2 \\]\n\n\\end{document}`,
      mathml_content: `<math><mi>E</mi><mo>=</mo><mi>m</mi><msup><mi>c</mi><mn>2</mn></msup></math>`,
      mml: `<mml:math xmlns:mml="http://www.w3.org/1998/Math/MathML"><mml:mi>E</mml:mi><mml:mo>=</mml:mo><mml:mi>m</mml:mi><mml:msup><mml:mi>c</mml:mi><mml:mn>2</mml:mn></mml:msup></mml:math>`,
      rendered_image_path: 'https://images.pexels.com/photos/3729557/pexels-photo-3729557.jpeg?auto=compress&cs=tinysrgb&w=800', // Placeholder
      created_at: new Date().toISOString(),
    };
    this.results[fileId] = mockResult;
  }

  // Auth Operations
  async getCurrentUser() {
    return this.currentUser;
  }

  async signIn() {
    await this.delay(500);
    return { user: this.currentUser, error: null };
  }

  async signOut() {
    await this.delay(200);
    return { error: null };
  }

  private delay(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

export const mockService = new MockStore();

