import * as React from 'react';
import { Box, Typography, Paper, CircularProgress, Alert } from '@mui/material';
import { useResource } from '../hooks/useResource';
import GenericForm from './GenericForm';
import { ConfigContext } from '../App';

export default function ProfileView() {
  const appConfig = React.useContext(ConfigContext);
  const profileConfig = appConfig?.profile;
  const resourceConfig = appConfig?.resources.find(r => r.name === profileConfig?.resource);

  if (!profileConfig || !resourceConfig) {
    return <Alert severity="error">Profile configuration not found.</Alert>;
  }

  // Create a modified config where only extraFields are editable
  const editableConfig = React.useMemo(() => {
    const newFields = { ...resourceConfig.fields };
    const extraFields = profileConfig.extraFields || [];
    
    Object.keys(newFields).forEach(key => {
      newFields[key] = {
        ...newFields[key],
        readOnly: !extraFields.includes(key),
      };
    });

    return {
      ...resourceConfig,
      fields: newFields,
    };
  }, [resourceConfig, profileConfig.extraFields]);

  const { useMe, useUpdateMe } = useResource(resourceConfig);
  const { data: profile, isLoading, error } = useMe();
  const updateMutation = useUpdateMe();

  const handleSave = async (formData: any) => {
    try {
      // Only send editable fields to prevent accidental overwrites of read-only data
      const extraFields = profileConfig.extraFields || [];
      const dataToSave = Object.keys(formData)
        .filter(key => extraFields.includes(key))
        .reduce((obj: any, key) => {
          obj[key] = formData[key];
          return obj;
        }, {});

      await updateMutation.mutateAsync(dataToSave);
    } catch (err) {
      console.error('Profile update failed:', err);
    }
  };

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return <Alert severity="error">Failed to load profile data.</Alert>;
  }

  return (
    <Box sx={{ maxWidth: 800, mx: 'auto', mt: 4 }}>
      <Typography variant="h4" gutterBottom>
        My Profile
      </Typography>
      <Paper sx={{ p: 4, mt: 2 }}>
        <GenericForm
          config={editableConfig}
          initialData={profile}
          onSave={handleSave}
          onCancel={() => window.history.back()}
          loading={updateMutation.isPending}
        />
      </Paper>
    </Box>
  );
}
