// app/dev/api-check/page.tsx (V2 - Com Mocks e Seções Colapsáveis)

"use client";

import React, { useState } from 'react';
import {
  authService,
  userService,
  patientService,
  doctorService,
  scheduleService,
  reportService,
} from '@/services/api/apiService';
import * as TestData from '@/services/api/apiTestData';
import {
  LoginResponse, SendMagicLinkResponse, LogoutResponse, GetCurrentUserResponse,
  RequestPasswordResetResponse, HardDeleteUserResponse, RegisterPatientResponse,
  ListResponse, Patient, GetAvailableSlotsResponse
} from '@/services/api/types';

type ApiResponse = { status: number | 'network_error'; data?: any; error?: Error };

const getStyleForResponse = (response: ApiResponse | null): React.CSSProperties => {
  if (!response) return {};
  const baseStyle: React.CSSProperties = { padding: '10px', border: '1px solid', borderRadius: '4px', whiteSpace: 'pre-wrap', wordBreak: 'break-all', marginTop: '10px' };
  if (response.status === 'network_error') return { ...baseStyle, backgroundColor: 'lightgoldenrodyellow', borderColor: 'goldenrod' };
  if (response.status >= 200 && response.status < 300) return { ...baseStyle, backgroundColor: 'lightgreen', borderColor: 'green' };
  if (response.status >= 400) return { ...baseStyle, backgroundColor: 'lightcoral', borderColor: 'darkred' };
  return {};
};

const ApiVerificationPage: React.FC = () => {
  // --- ESTADOS ---
  const [loginData, setLoginData] = useState(TestData.loginTestData.success);
  const [loginResponse, setLoginResponse] = useState<LoginResponse | null>(null);
  const [magicLinkEmail, setMagicLinkEmail] = useState(TestData.magicLinkTestData.success);
  const [magicLinkResponse, setMagicLinkResponse] = useState<SendMagicLinkResponse | null>(null);
  const [logoutResponse, setLogoutResponse] = useState<LogoutResponse | null>(null);
  const [currentUserResponse, setCurrentUserResponse] = useState<GetCurrentUserResponse | null>(null);
  const [resetPassData, setResetPassData] = useState(TestData.resetPassTestData.success);
  const [resetPassResponse, setResetPassResponse] = useState<RequestPasswordResetResponse | null>(null);
  const [deleteUserData, setDeleteUserData] = useState(TestData.deleteUserTestData.success);
  const [deleteUserResponse, setDeleteUserResponse] = useState<HardDeleteUserResponse | null>(null);
  const [registerPatientData, setRegisterPatientData] = useState(TestData.registerPatientTestData.success);
  const [registerPatientResponse, setRegisterPatientResponse] = useState<RegisterPatientResponse | null>(null);
  const [listPatientsFilter, setListPatientsFilter] = useState(TestData.listPatientsTestData.success);
  const [listPatientsResponse, setListPatientsResponse] = useState<ListResponse<Patient> | null>(null);
  const [slotsData, setSlotsData] = useState(TestData.slotsTestData.success);
  const [slotsResponse, setSlotsResponse] = useState<GetAvailableSlotsResponse | null>(null);

  // --- HANDLERS ---
  const handleApiCall = async (apiFunction: (...args: any[]) => Promise<any>, payload: any, setResponse: React.Dispatch<React.SetStateAction<any>>) => {
    setResponse(null);
    const response = await apiFunction(payload);
    setResponse(response);
  };
  const handleApiCallNoPayload = async (apiFunction: () => Promise<any>, setResponse: React.Dispatch<React.SetStateAction<any>>) => {
    setResponse(null);
    const response = await apiFunction();
    setResponse(response);
  };
  const handleRequestPasswordReset = async () => {
    setResetPassResponse(null);
    const response = await userService.requestPasswordReset(resetPassData.email, resetPassData.redirectUrl || undefined);
    setResetPassResponse(response);
  };
  const handleGetAvailableSlots = async () => {
    setSlotsResponse(null);
    const response = await scheduleService.getAvailableSlots(slotsData.doctorId, slotsData.date);
    setSlotsResponse(response);
  };

  return (
    <div style={{ fontFamily: 'sans-serif', padding: '20px', maxWidth: '1000px', margin: 'auto' }}>
      <h1>Painel de Verificação da API</h1>
      <p>Use este painel para executar cada função do `apiService` e verificar o objeto de resposta completo.</p>

      <details open>
        <summary><h2>Autenticação</h2></summary>
        <div className="test-block">
          <details>
            <summary><h3>authService.login</h3></summary>
            <div className="controls">
              <button onClick={() => setLoginData(TestData.loginTestData.success)}>Carregar Sucesso</button>
              <button onClick={() => setLoginData(TestData.loginTestData.error)}>Carregar Erro</button>
            </div>
            <pre>{JSON.stringify(loginData, null, 2)}</pre>
            <button onClick={() => handleApiCall(authService.login, loginData, setLoginResponse)}>Executar</button>
            {loginResponse && <pre style={getStyleForResponse(loginResponse)}>{JSON.stringify(loginResponse, null, 2)}</pre>}
          </details>
        </div>
        <div className="test-block">
          <details>
            <summary><h3>authService.sendMagicLink</h3></summary>
            <div className="controls">
                <button onClick={() => setMagicLinkEmail(TestData.magicLinkTestData.success)}>Carregar Sucesso</button>
                <button onClick={() => setMagicLinkEmail(TestData.magicLinkTestData.error)}>Carregar Erro</button>
            </div>
            <pre>{JSON.stringify(magicLinkEmail, null, 2)}</pre>
            <button onClick={() => handleApiCall(authService.sendMagicLink, magicLinkEmail.email, setMagicLinkResponse)}>Executar</button>
            {magicLinkResponse && <pre style={getStyleForResponse(magicLinkResponse)}>{JSON.stringify(magicLinkResponse, null, 2)}</pre>}
          </details>
        </div>
        <div className="test-block">
          <details>
            <summary><h3>authService.logout</h3></summary>
            <button onClick={() => handleApiCallNoPayload(authService.logout, setLogoutResponse)}>Executar</button>
            {logoutResponse && <pre style={getStyleForResponse(logoutResponse)}>{JSON.stringify(logoutResponse, null, 2)}</pre>}
          </details>
        </div>
        <div className="test-block">
          <details>
            <summary><h3>authService.getCurrentUser</h3></summary>
            <button onClick={() => handleApiCallNoPayload(authService.getCurrentUser, setCurrentUserResponse)}>Executar</button>
            {currentUserResponse && <pre style={getStyleForResponse(currentUserResponse)}>{JSON.stringify(currentUserResponse, null, 2)}</pre>}
          </details>
        </div>
      </details>

      <details open>
        <summary><h2>Usuários</h2></summary>
        <div className="test-block">
          <details>
            <summary><h3>userService.requestPasswordReset</h3></summary>
            <div className="controls">
                <button onClick={() => setResetPassData(TestData.resetPassTestData.success)}>Carregar Sucesso</button>
                <button onClick={() => setResetPassData(TestData.resetPassTestData.error)}>Carregar Erro</button>
            </div>
            <pre>{JSON.stringify(resetPassData, null, 2)}</pre>
            <button onClick={handleRequestPasswordReset}>Executar</button>
            {resetPassResponse && <pre style={getStyleForResponse(resetPassResponse)}>{JSON.stringify(resetPassResponse, null, 2)}</pre>}
          </details>
        </div>
        <div className="test-block">
          <details>
            <summary><h3>userService.hardDeleteUser_DANGEROUS</h3></summary>
            <div className="controls">
                <button onClick={() => setDeleteUserData(TestData.deleteUserTestData.success)}>Carregar Sucesso</button>
                <button onClick={() => setDeleteUserData(TestData.deleteUserTestData.error)}>Carregar Erro</button>
            </div>
            <pre>{JSON.stringify(deleteUserData, null, 2)}</pre>
            <button onClick={() => handleApiCall(userService.hardDeleteUser_DANGEROUS, deleteUserData.userId, setDeleteUserResponse)}>Executar</button>
            {deleteUserResponse && <pre style={getStyleForResponse(deleteUserResponse)}>{JSON.stringify(deleteUserResponse, null, 2)}</pre>}
          </details>
        </div>
      </details>

      <details open>
        <summary><h2>Pacientes</h2></summary>
        <div className="test-block">
          <details>
            <summary><h3>patientService.registerPatient</h3></summary>
            <div className="controls">
                <button onClick={() => setRegisterPatientData(TestData.registerPatientTestData.success)}>Carregar Sucesso</button>
                <button onClick={() => setRegisterPatientData(TestData.registerPatientTestData.errorValidation)}>Carregar Erro (Validação)</button>
                <button onClick={() => setRegisterPatientData(TestData.registerPatientTestData.errorConflict)}>Carregar Erro (Conflito)</button>
            </div>
            <pre>{JSON.stringify(registerPatientData, null, 2)}</pre>
            <button onClick={() => handleApiCall(patientService.registerPatient, registerPatientData, setRegisterPatientResponse)}>Executar</button>
            {registerPatientResponse && <pre style={getStyleForResponse(registerPatientResponse)}>{JSON.stringify(registerPatientResponse, null, 2)}</pre>}
          </details>
        </div>
        <div className="test-block">
          <details>
            <summary><h3>patientService.list</h3></summary>
            <div className="controls">
                <button onClick={() => setListPatientsFilter(TestData.listPatientsTestData.success)}>Carregar com Filtro</button>
                <button onClick={() => setListPatientsFilter(TestData.listPatientsTestData.noFilter)}>Carregar Sem Filtro</button>
            </div>
            <pre>{JSON.stringify(listPatientsFilter, null, 2)}</pre>
            <button onClick={() => handleApiCall(patientService.list, listPatientsFilter, setListPatientsResponse)}>Executar</button>
            {listPatientsResponse && <pre style={getStyleForResponse(listPatientsResponse)}>{JSON.stringify(listPatientsResponse, null, 2)}</pre>}
          </details>
        </div>
      </details>
      
      <details open>
        <summary><h2>Agendamentos</h2></summary>
        <div className="test-block">
          <details>
            <summary><h3>scheduleService.getAvailableSlots</h3></summary>
            <div className="controls">
                <button onClick={() => setSlotsData(TestData.slotsTestData.success)}>Carregar Sucesso</button>
                <button onClick={() => setSlotsData(TestData.slotsTestData.error)}>Carregar Erro</button>
            </div>
            <pre>{JSON.stringify(slotsData, null, 2)}</pre>
            <button onClick={handleGetAvailableSlots}>Executar</button>
            {slotsResponse && <pre style={getStyleForResponse(slotsResponse)}>{JSON.stringify(slotsResponse, null, 2)}</pre>}
          </details>
        </div>
      </details>

      <style>{`
        h2 { margin-top: 20px; border-bottom: 2px solid #eee; padding-bottom: 5px; }
        summary { cursor: pointer; font-size: 1.2em; font-weight: bold; }
        details { margin-bottom: 10px; }
        .test-block { border: 1px solid #ccc; padding: 15px; margin-top: 10px; border-radius: 5px; }
        .controls button { margin-right: 10px; }
        button { margin-top: 10px; margin-bottom: 10px; padding: 8px 12px; cursor: pointer; border-radius: 4px; border: 1px solid #666; }
        pre { margin-top: 10px; }
      `}</style>
    </div>
  );
};

export default ApiVerificationPage;